文章目录
1. 实施处理程序
1.1 ansible处理程序
Ansible模块设计为具有幂等性。这表示,在正确编写的playbook中,playbook及其任务可以运行多次而不会改变受管主机,除非需要进行更改使受管主机进入所需的状态。
但在时候,在任务确实更改系统时,可能需要运行进一步的任务。例如,更改服务配置文件时可能要求重新加载该服务以便使其更改的配置生效。
处理程序是响应由其他任务触发的通知的任务。仅当任务在受管主机上更改了某些内容时,任务才通知其处理程序。每个处理程序具有全局唯一的名称,在playbook中任务块的末尾触发。如果没有任务通过名称通知处理程序,处理程序就不会运行。如果一个或多个任务通知处理程序,处理程序就会在play中的所有其他任务完成后运行一次。因为处理程序就是任务,所以可以在处理程序中使用他们将用于任何其他任务的模块。通常而言,处理程序被用于重新引导主机和重启服务。
处理程序可视为非活动任务,只有在使用notify语句显式调用时才会被触发。在下列代码片段中,只有配置文件更新并且通知了该任务,restart httpd处理程序才会重启Apache服务器:
---
- host: 192.168.101.200
tasks:
- name: install apache
yum:
name: httpd
state: present
- name: service httpd
service:
name: httpd
state: restarted
enabled: yes
- name: config httpd
copy:
src: files/httpd.conf
dest: /etc/httpd/conf.d/httpd.conf
notify:
- restart httpd
handlers:
- name: restart httpd
service:
name: httpd
state: restarted
tasks:
- name: config httpd
template:
src: files/httpd.conf
dest: /etc/httpd/conf.d/httpd.conf
notify:
- restart mysql
- restart apache
handlers:
- name: restart mysql
service:
name: mariadb
state: restarted
- name: restart apache
service:
name: httpd
state: rest