1、handlers的概念
handlers是另一种’任务列表’,handlers中的任务会被tasks中的任务进行”调用”,但是,被”调用”并不意味着一定会执行,只有当tasks中的任务”真正执行”以后(真正的进行实际操作,造成了实际的改变),handlers中被调用的任务才会执行,如果tasks中的任务并没有做出任何实际的操作,那么handlers中的任务即使被’调用’,也并不会执行。
示例如下:(举例不代表实际应用)
- hosts: all
remote_user: root
tasks:
- name: httpd install
yum: name=httpd state=latest
- name: httpd start
service: name=httpd state=started
- name: httpd file update
copy: src=files/httpd.conf dest=/etc/httpd/conf/
notify: restart httpd
- name: web configfile
copy: src=files/www.cityhouse.cn.conf dest=/etc/httpd/conf/conf.d/
notify: web configfile
handlers:
- name: restart httpd
service: name=httpd state=restarted
- name: web configfile
service: name=httpd state=restarted
如果httpd.conf文件没有改变则不需要重启httpd,如果httpd.conf文件有变化则触发handlers
2、meta模块
如上图所示,默认情况下,所有task执行完毕后,才会执行各个handler,并不是执行完某个task后,立即执行对应的handler,如果你想要在执行完某些task以后立即执行对应的handler,则需要使用meta模块,
示例如下:(举例不代表实际应用)
- hosts: all
remote_user: root
tasks:
- name: httpd install
yum: name=httpd state=latest
- name: httpd start
service: name=httpd state=started
- name: httpd file update
copy: src=files/httpd.conf dest=/etc/httpd/conf/
notify: restart httpd
- meta: flush_handlers
- name: web configfile
copy: src=files/www.cityhouse.cn.conf dest=/etc/httpd/conf/conf.d/
notify: restart httpd
handlers:
- name: restart httpd
service: name=httpd state=restarted
- name: web configfile
service: name=httpd state=restarted
如上例所示,在当前meta任务之前,一共有3个任务,task1、task2和task3,task3和task4有对应的handler,当执行完task1、task2、task3以后,立即执行对应的handler,而不是像默认情况那样在所有任务都执行完毕以后才能执行所有handlers,
如果想要每个task在实际操作后都立马执行对应handlers,则可以在每个任务之后都添加一个meta任务,并将其值设置为flush_handlers。 所以,我们可以依靠meta任务,让handler的使用变得更加灵活。
3、一个task中调用多个handler
怎样才能一次性notify多个handler呢?你可能会尝试将多个handler使用相同的name,但是这样并不可行,因为当多个handler的name相同时,只有一个handler会被执行,所以,我们并不能通过这种方式notify多个handler,如果想要一次notify多个handler,则需要借助另一个关键字"listen",你可以把listen理解成”组名”,我们可以把多个handler分成”组”,当我们需要一次性notify多个handler时,只要将多个handler分为”一组”,使用相同的”组名”即可,当notify对应的值为”组名”时,”组”内的所有handler都会被notify.
示例如下:(举例不代表实际应用)
---
- hosts: all
remote_user: root
tasks:
- name: httpd install
yum: name=httpd state=latest
- name: httpd start
service: name=httpd state=started
- name: httpd file update
copy: src=files/httpd.conf dest=/etc/httpd/conf/
notify: httpd group1
handlers:
- name: httpd webfile
listen: httpd group1
copy: src=files/www.cityhouse.cn.conf dest=/etc/httpd/conf/conf.d/
- name: httpd restart
listen: httpd group1
service: name=httpd state=restarted
如上例所示,httpd webfile与httpd restart的listen的值都是httpd group1,当httpd file update中notify的值为httpd group1时,httpd webfile与httpd restart都会被notify(调用)