ansible playbook中的handlers
2018-08-08
ansible playbook 中的 handlers
执行 task 之后,服务器发生变化之后要执行的一些操作,比如修改了配置文件之后,需要重启一下服务,那么必须确保配置文件真的被修改了,才能重启。
例:
[root@server ansible]# vim handlers.yml
---
- hosts: client.test.com
name: handlers test
user: root
tasks:
- name: copy file
copy: src=/etc/passwd dest=/tmp/aaa.txt
notify: test handlers
handlers:
- name: test handlers
shell: echo "11111" >> /tmp/aaa.txt
[root@server ansible]# ansible-playbook handlers.yml
PLAY [handlers test] ***********************************************************
TASK [setup] *******************************************************************
ok: [client.test.com]
TASK [copy file] ***************************************************************
changed: [client.test.com]
RUNNING HANDLER [test handlers] ************************************************
changed: [client.test.com]
PLAY RECAP *********************************************************************
client.test.com : ok=3 changed=2 unreachable=0 failed=0
查看一下 aaa.txt
[root@server ansible]# ansible client.test.com -m shell -a "tail -5 /tmp/aaa.txt"
client.test.com | SUCCESS | rc=0 >>
apache:x:48:48:Apache:/var/www:/sbin/nologin
nrpe:x:497:498:NRPE user for the NRPE service:/var/run/nrpe:/sbin/nologin
puppet:x:52:52:Puppet:/var/lib/puppet:/sbin/nologin
test:x:500:500::/home/test:/bin/bash
11111
可以看到 passwd 文件复制过去了,11111 也被追加,此操作是在 passwd 和 aaa.txt 文件内容不一致的前提下完成的,如果两者内容一样,copy 不会执行,handlers 就不会被调用。试验一下:
先把 passwd 复制到 aaa.txt
[root@server ansible]# rsync -av /etc/passwd client.test.com:/tmp/aaa.txt
sending incremental file list
passwd
sent 634 bytes received 43 bytes 1354.00 bytes/sec
total size is 1256 speedup is 1.86
再去执行:
[root@server ansible]# ansible-playbook handlers.yml
PLAY [handlers test] ***********************************************************
TASK [setup] *******************************************************************
ok: [client.test.com]
TASK [copy file] ***************************************************************
ok: [client.test.com]
PLAY RECAP *********************************************************************
client.test.com : ok=2 changed=0 unreachable=0 failed=0
查看一下,没有 11111 了
[root@server ansible]# ansible client.test.com -m shell -a "tail -5 /tmp/aaa.txt"
client.test.com | SUCCESS | rc=0 >>
rpc:x:32:32:Rpcbind Daemon:/var/cache/rpcbind:/sbin/nologin
apache:x:48:48:Apache:/var/www:/sbin/nologin
nrpe:x:497:498:NRPE user for the NRPE service:/var/run/nrpe:/sbin/nologin
puppet:x:52:52:Puppet:/var/lib/puppet:/sbin/nologin
test:x:500:500::/home/test:/bin/bash