ansible playbook 用法
1. ansible playbook 介绍playbook 就是相当于把模块或函数写入到配置文件里面,然后我们执行该配置文件来达到远程运维自动化的目的,类似 shell 脚本
# cat /etc/ansible/test.yml # playbook 文件以 yml 结尾
--- # --- 为固定格式,不能省略,包括 hosts 前面的 -
- hosts: test_hosts # hosts 指定对哪些主机组或者ip进行操作
remote_user: root # remote_user 指定执行远程命令的用户
tasks: # tasks 指定任务,先对任务进行命名,再写要执行的命令
- name: test_playbook # name 对任务进行一个描述,执行过程中会打印出来
shell: touch /tmp/1.txt # shell 具体要执行的命令
# ansible-playbook /etc/ansible/test.yml # 执行 playbook
2. ansible playbook 循环语句
如下,使用循环分别修改远程主机三个文件的权限及属主属组,其中 {{ item }} 和 with_items 是固定的写法
---
- hosts: test_hosts
remote_user: root
tasks:
- name: test_playbook
file: path=/tmp/{{ item }} mode=600 owner=root group=root
with_items:
- 1.txt
- 2.txt
- 3.txt
3. ansible playbook 判断语句
如下,首先 gather_facts 用于获取远程主机的 ansible 变量,就像执行 env 命令一样,最后在 tasks 中使用 when 可以进行判断
(具体有什么变量可以通过 ansible 192.168.5.134 -m setup 来获取,其中 192.168.5.134 是远程主机,也可以写成主机组)
---
- hosts: test_hosts
remote_user: root
gather_facts: True
tasks:
- name: test_playbook
shell: touch /tmp/1.txt
when: facter_ipaddress == "192.168.5.134"
4. ansible playbook handlers
handlers 的目的是在执行完成 tasks 之后,还需要进行其他的操作时,使用 handlers,但是这里需要保证只有在 tasks 执行成功之后,handlers 才会生效,这种比较适合配置文件发生更改后,自动重启服务的操作,比如使用 tasks 更改了 nginx 的配置文件,然后我们再使用 handlers 来重新加载 nginx
如下,当 touch /tmp/1.txt 执行成功之后,再执行 handlers 中的 touch /tmp/2.txt
---
- hosts: test_hosts
remote_user: root
tasks:
- name: test_playbook
shell: touch /tmp/1.txt
notify: test handlers # 指定 notify ,作用是当上面的命令成功之后就执行下面的 handlers
handlers:
- name: test handlers # handlers 的名字要与上面 notify 定义的一致
shell: touch /tmp/2.txt
页:
[1]