ansible之notify与handler
2019-05-06 本文已影响112人
燃燃的爸爸
handler,用来执行某些条件下的任务,比如当配置文件发生变化的时候,通过notify触发handler去重启服务。
精髓所在:你可能会想这个功能有什么作用,我在下面多执行几个play不就完了?
其实他的特点是:
1.“notify”这个action可用于在每个play的最后被触发,这样可以避免多次有改变发生时每次都执行指定的操作,取而代之,仅在所
2.有的变化发生完成后一次性地执行指定操作。在notify中列出的操作称为handler,也即notify中调用handler中定义的操作。
- hosts: local
remote_user: zing
tasks:
- name: copy properties
copy: src=/home/zing/project.properties dest=/home/java/pro/project.properties
- name:
file: path=/home/java/pro/project.properties mode=600
notify:
- restart server
handlers:
- name: restart server
service: name=tomcat state=restarted
案例2:
heartbeat.yaml
-hosts: hbhosts
remote_user: root
tasks:
- name: ensure heartbeat latest version
yum: name=heartbeat state=present
- name: authkeys configure file
copy: src=/root/hb_conf/authkeysdest=/etc/ha.d/authkeys
- name: authkeys mode 600
file: path=/etc/ha.d/authkeys mode=600
notify:
- restart heartbeat
- name: ha.cf configure file
copy: src=/root/hb_conf/ha.cfdest=/etc/ha.d/ha.cf
notify:
-restart heartbeat
handlers:
- name:restart heartbeat
service: name=heartbeat state=restarted
个人项目中的一个案例:
#先判断centos6还是7 然后根据区别去做自启动服务,然后开启nginx服务
- name: config power on service in centos6
shell: "cp -p {{ tengine_git_path }}/nginx /etc/init.d/;chkconfig nginx on "
when: ansible_distribution == 'CentOS' and ansible_distribution_major_version == "6"
notify:
- start nginx
- name: config power on service in centos7
shell: "cp -p {{ tengine_git_path }}/nginx.service /usr/lib/systemd/system/;systemctl enable nginx.service"
when: ansible_distribution == 'CentOS' and ansible_distribution_major_version == "7"
notify:
- start nginx