Ansible Playbook示例 hello world

剧本是以yaml格式编写的,您实际上可以选择在哪里存储剧本。在我的例子中,我将创建一个名为playbooks的文件夹来存储我的playbooks,我将在root用户的主目录中创建它:

[root@controller ~]# pwd
/root
[root@controller ~]# mkdir playbooks
[root@controller ~]# cd playbooks
[root@controller playbooks]# pwd
/root/playbooks

在这个目录中,我将创建一个名为HelloWorld.yml的yaml文件:

--
- name: This is a hello-world example
  hosts: ansibleclient01.local
  tasks:
    - name: Create a file called '/tmp/testfile.txt' with the content 'hello world'.
      copy:
        content: hello worldn
        dest: /tmp/testfile.txt

本剧本旨在使用ansible的复制模块在客户端ansibleclient01.local上创建文件/tmp/testfile.txt。
您可以将此剧本视为可以执行的脚本。您可以使用ansible playbook命令执行此playbook:

[root@controller playbooks]# ansible-playbook HelloWorld.yml
PLAY [This is a hello-world example] ***
TASK [setup] ***
ok: [ansibleclient01.local]
TASK [Create a file called '/tmp/testfile.txt' with the content 'hello world'.]
changed: [ansibleclient01.local]
PLAY RECAP *
ansibleclient01.local : ok=2 changed=1 unreachable=0 failed=0

这导致在客户端上创建以下文件:

[root@ansibleclient01 /]# cat /tmp/testfile.txt
hello world

现在让我们删除testfile.txt。然后返回控制器。现在让我们以另一种方式创建testfile.txt,这次使用的是静态文件。我们首先创建一个静态文件并将其放置在一个逻辑位置。在我的例子中,我创建了一个名为files的文件夹,并将testfile.txt放其中:

[root@controller playbooks]# tree
.
├── files
│     └── testfile.txt
└── HelloWorld.yml
1 directory, 2 files
[root@controller playbooks]# cat files/testfile.txt
hello world

然后,在HelloWorld.yml文件中,我将复制模块的内容属性更改为src:

--
- name: This is a hello-world example
  hosts: ansibleclient01.local
  tasks:
    - name: Create a file called '/tmp/testfile.txt' with the content 'hello world'.
    copy:
      src: ./files/testfile.txt
      dest: /tmp/testfile.txt

注意,我认为src路径是相对于playbook的位置的。您可以使用绝对路径,但这会使将静态文件移动到其他位置变得不灵活。

日期:2020-07-07 20:57:25 来源:oir作者:oir