十二、Ansible playbook

简介

前面学过shell脚本,我们知道当多条shell命令放在一个文件中执行(这个文件以.sh后缀命名),这个文件就被称为脚本;脚本中的不同的shell命令可以用来执行不同的功能。

playbook就相当于脚本,它是由一个或多个play组成,play就是用来执行不同的功能的。

playbook文件以.yal或者.yml为文件名后缀。

单个play运行案例

实验要求:
1、使用ping检测一下db_servers资源里的远程主机;
2、在这些远程主机上创建路径为/testdir/test的目录。

这里给出ad-hoc跟playbook两种写法用来对比之间的差异
1、ad-hoc命令格式写法如下

$ ansible db_servers -m ping
$ ansible db_servers -m file -a "path=/testdir/test state=directory"

2、playbook格式写法如下
test.yml文件内容如下,这里只写了一个play

说明

--- #表示文档开始
- hosts: db_servers,web_servers #-表示一个块序列的节点,hosts关键字指定要操作的主机,多台主机用逗号隔开,注意-跟:后必须有空格
  remote_user: root #表示使用远程主机的root账户进行操作,冒号后有空格
  tasks: #指明要操作的任务列表
  - name: Ping the host #任务名,可以自定义
    ping: #使用ping模块
  - name: make directory test #任务名,可以自定义
    file: #使用file模块
      path: /testdir/test #指定file模块参数path,注意冒号后有空格
      state: directory #指定state参数,注意冒号后有空格

3、运行效果

说明

PLAY [db_servers] #表示此play是针对db_servers资源里的远程主机运行的,一个playbook可以由一个或多个play组成,如果把playbook看成剧本,play就相当于其中的章节。

TASK [Gathering Facts] #每个play在执行时都会先执行这个默认任务,’Gathering Facts’这个默认任务会收集当前play对应的目标主机的相关信息,收集完信息后,才会执行我们指定的任务
ok: [10.154.0.110]

TASK [Ping the host] #ping模块执行结果
ok: [10.154.0.110]

TASK [make directory test] #file模块执行结果
changed: [10.154.0.110]

PLAY RECAP #汇总报告
10.154.0.110               : ok=3    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0 

多个play运行案例

test.yml文件内容如下

执行效果


playbook的其他写法

实验要求
1、在db_servers远程主机上使用root用户创建/testdir/testfile文件
2、/testdir/testfile文件权限为0700

写法一

---
- hosts: db_servers
  remote_user: root
  tasks:
  - name: make testfile
    file:
      path: /testdir/testfile
      state: touch
      mode: 0700

写法二

---
- hosts: db_servers
  remote_user: root
  tasks:
  - name: make testfile
    file: path=/testdir/testfile state=touch mode=0700

相关命令

1、运行playbook

$ ansible-playbook /root/temp_script/test.yml

2、语法检查

$ ansible-playbook --syntax-check /root/temp_script/test.yml

playbook: /root/temp_script/test.yml #返回playbook名称,表示没有语法错误

3、模拟执行

$ ansible-playbook --check test.yml

模拟执行并不是真正执行,只是'假装'执行,可以帮助我们提前'预估'playbook是否能够正常执行。
注意:使用模拟执行时,一些任务可能会报错,如先创建test目录,进入test目录后创建test.py文件,因为是模拟运行,test目录并不会真正的被创建,所以后续任务会报错。


参考资料:
转载于朱老师博客

posted @ 2021-06-11 11:48  努力吧阿团  阅读(123)  评论(0)    收藏  举报