Ansible教程(4)playbook的handlers与notify
一、Ansible handlers的作用
handlers是一种触发器,它可以对task进行监控,如果task所指定的任务状态发生变化,则进行notify通知,然后触发额外的一系列操作,看一个示例来帮助理解:
cat apache.yml - hosts: webservers remote_user: root tasks: - name: install apache yum: name=httpd state=latest - name: install configure file for httpd copy: src=/root/conf/httpd.conf dest=/etc/httpd/conf/httpd.conf - name: start httpd service service: enabled=true name=httpd state=started
上面的YAML文件存在三个task任务,分别是安装httpd、复制配置文件到远端主机、启动httpd服务。但是当第二个task中的配置文件发生了改变后再次执行playbook的话,会发现新的配置文件虽然会正确的复制到远端主机去,但是却没有重启httpd服务。因为Ansible在执行playbook时发现第三个任务与现在状态是一致的,就不会再次执行任务。为了解决这种问题,就需要使用ansible的handlers功能。handlers是用于监控一个任务的执行状态,如果一个tasks任务最后是changed状态则会触发handlers指定的操作。
二、如何配置handlers
Ansible中通过notify这个模块来实现handlers,将示例1修改后:
cat apache.yml - hosts: webservers remote_user: root tasks: - name: install apache yum: name=httpd state=latest - name: install configure file for httpd copy: src=/root/conf/httpd.conf dest=/etc/httpd/conf/httpd.conf notify: - restart httpd #通知restart httpd这个触发器 - check httpd #可以定义多个触发器 - name: start httpd service service: enabled=true name=httpd state=started handlers: #定义触发器,和tasks同级 - name: restart httpd #触发器名字,被notify引用,两边要一致 service: name=httpd state=restart - name: check httpd shell: netstat -ntulp | grep 80
当httpd.conf的源文件发生修改后,只需重新执行playbook就会自动重启httpd服务,因为配置文件状态是changed而非ok。
版权声明:如无特殊标注,文章均为本站原创,转载时请以链接形式注明文章出处。
评论