Ansible——handlers与notify

handlers

当我们修改了配置文件后,需要重启服务时,可以利用handlers中的tasks。避免不必要的重启。只要等配置文件修改的时候,才会触发handlers。

notify

handlers中的任务无法直接使用,需要通过notify来调用handlers。

注意:

  1. 调用时根据handlers的名字来确认。所以一个playbook中,handlers的名字一定是唯一的。
  2. notify用于在每个play的最后被触发。无论通过notify调用几次handlers。系统都会在所有play完成后才执行一次handlers中的任务。

实例:

题目:修改apache配置文件后才重启httpd服务。如果没有改变则不重启。

  1. 执行playbook发现没有执行handlers,因为模板中的变量并没有发生变化。从而不会触发handlers
[root@localhost project]# vim ceshi2.yml
---
- name: handlers
  vars_files:
    files/vars
  hosts: 192.168.190.133
  tasks:
    - template:
        src: template/vhosts.j2
        dest: /etc/httpd/conf.d/vhosts.conf
      notify:
        restart apache
  handlers:
    - name: restart apache
      service:
        name: httpd
        state: restarted

TASK [template] ****************************************************************************************
ok: [192.168.190.133]

PLAY RECAP *********************************************************************************************
192.168.190.133            : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0
  1. 修改变量的值
[root@localhost project]# vim files/vars   修改外部变量文件中的端口号 从81变为9528
port_name1: 80
port_name2: 9528
service1_name: web_1
service2_name: web_2
  1. 再次执行playbook,发现handlers成功执行
[root@localhost project]# ansible-playbook ceshi2.yml 

......
RUNNING HANDLER [restart apache] ***********************************************************************
changed: [192.168.190.133]

PLAY RECAP *********************************************************************************************
192.168.190.133            : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

4.查看被控机的端口号是否改变

[root@localhost project]# ansible 192.168.190.133 -a 'ss -antl' -i inventory 
192.168.190.133 | CHANGED | rc=0 >>
State    Recv-Q    Send-Q        Local Address:Port        Peer Address:Port    
LISTEN   0         128                 0.0.0.0:22               0.0.0.0:*       
LISTEN   0         25                  0.0.0.0:514              0.0.0.0:*       
LISTEN   0         128                       *:80                     *:*       
LISTEN   0         128                    [::]:22                  [::]:*       
LISTEN   0         128                       *:9528                   *:*        80与9528端口都被开启
LISTEN   0         25                     [::]:514                 [::]:* 


posted @ 2020-09-06 16:13  阿不思布丁  阅读(471)  评论(0编辑  收藏  举报