ansible的handlers处理器和notify通知
handlers处理器和notify通知的作用
handlers的作用是用来检测tasks的状态,当tasks的状态达到预期要求后,会执行指定的操作。
notify的作用是通知handlers处理器执行任务。
实战中handlers主要用于重启service。
例如:修改了配置文件后必须重启service,但不是每次运行playbook都做了配置修改,notify能检测配置状态为changed时,才通知handlers执行重启service。notify没有修改配置就不通知handlers执行重启service。
handlers就是一个tasks,编写格式和tasks完全一致,只是把tasks关键字改成handlers。
handlers在一个play中是可以被复用的,play中的其他tasks是可以调用handlers的。
---
- name: handlers演示剧本
hosts: all
tasks:
- name: 先创建一个目录
file:
path: /tmp/parents/subdir/
state: directory
notify: touch file
handlers:
- name: touch file # touch file这个任务要求先创建好目录(状态为change)才能执行下面的下面的任务
file:
path: /tmp/parents/subdir/new.txt
state: touch
- 执行结果
[c8 root /tmp]# cd parents/subdir/
[c8 root /tmp/parents/subdir]# ls
new.txt
[rhel7-gjb root /tmp]# cd parents/subdir/
[rhel7-gjb root /tmp/parents/subdir]# ls
new.txt
- 将new.txt文件删除再次执行剧本
创建目录这个任务不是change状态,没有执行touch file这一步
handlers处理器结合template模块检测配置变化
---
- name: 检测配置文件是否发生更改
template:
src: /var/lib/templates/demo.example.conf.template
dest: /var/lib/templates/demo.example.conf
nofity: # 如果检查到上面的配置文件状态为change
- restart apache # 就执行restart apache
handlers:
- name: restart apache
service:
name: httpd
state: restarted
综合练习
如果tasks运行错误,handlers是不运行的
这种情况下要加force_handlers,才会执行。
---
- name: Installing MariaDB server
hosts: databases
force_handlers: yes
vars:
db_packages:
- mariadb-server
- python3-PyMySQL
db_service: mariadb
resources_url: http://materials.example.com/labs/control-handlers
config_file_url: "{{ resources_url }}/my.cnf.standard"
config_file_dst: /etc/my.cnf
tasks:
- name: install_dbserver
yum:
name: "{{ db_packages }}"
state: latest
# install_dbserver状态为change时就执行set_db_password
notify: set_db_password
- name: start_dbserver_service
service:
name: "{{ db_service }}"
state: started
enabled: true
- name: download_db_cfg
get_url:
url: "{{ config_file_url }}"
dest: "{{ config_file_dst }}"
owner: mysql
group: mysql
force: yes
notify: restart_db_service
# dowanload_db_cfg状态为change时就重启db服务
handlers:
- name: restart_db_service
service:
name: "{{ db_service }}"
state: restarted
- name: set_db_password
mysql_user:
name: root
password: redhat