ansible笔记(11):初识ansible playbook(二)

ansible笔记(11):初识ansible playbook(二)

有前文作为基础,如下示例是非常容易理解的:

---
- hosts: test211
  remote_user: root
  tasks:
  - name: make testfile
    file:
      path: /data/testfile001
      state: touch
      mode: 0700

上例中有一个play,这个play针对test211主机运行,这个play的任务列表中只有一个任务,这个任务就是调用file模块,确保/data/testfile001文件存在并且testfile001文件的权限为0700,把上例中的任务列表部分单独截取出来,如下所示

  tasks:
  - name: make testfile
    file:
      path: /data/testfile001
      state: touch
      mode: 0700
正如你所看到的,"path: /data/testfile001" 表示为file模块的path参数赋值,我们使用"冒号"(冒号后有空格)对参数赋值。

其实,除了这种使用冒号的方式,我们还可以使用如下格式为模块的参数赋值
tasks:
- name: make testfile001
  file: path=/data/testfile001 state=touch mode=0700

如上所示,我们调用file模块时,设置了三个参数,path参数、state参数、mode参数,为参数赋值时,使用了"等号",每个参数之间使用空格隔开,这种格式也是完全正确的,如果你在使用一个模块时设置的参数比较多,那么使用上述格式设置参数时,这些参数可能会"挤在一行"里面,你也可以把它们分成多行去写,如下例所示

tasks:
- name: make testfile001
  file: path=/data/testfile001
  state=touch mode=0700
即使把多个参数分行写,也需要注意缩进。
上述书写格式都是0.8版本以后的ansible推荐的书写格式,在0.8版本之前,使用action关键字调用模块,示例如下:

tasks:
- name: make testfile001
  action: file path=/data/testfile001 state=touch mode=0700

如上例所示,使用action关键字调用对应的模块,在当前版本中(当前使用ansible版本为2.5)仍然兼容这种语法

在之前的示例中,我们对每个任务都指定了对应的名称,即每个task都有对应的name,当我们省略name时,默认以当前任务调用的模块的名称作为任务的名称,不过建议不要省略name,因为当任务存在name时,可读性比较高。

在编写任务时,我习惯将name属性写在任务的开头,当然,任务的各个属性并没有严格的顺序要求,如下两种写法的效果是相同的。
写法一:
tasks:
- name: make testfile001
  file: path=/data/testfile001
        state=touch
    mode=0700

写法二:
tasks:
- file: path=/data/testfile001
        state=touch
    mode=0700
  name: make testfile001

各属性顺序虽然没有要求,但是仍然需要严格按照缩进进行对齐。

猜你喜欢

转载自www.cnblogs.com/reblue520/p/9458615.html