这次介绍下handlers的用法

当我们要修改某些配置文件的时候,有的需要配置重载或者重新启动服务,比如修改nginx的 listen 80;修改为listen 8080;需要重载nginx。

  • hosts: docker
    remote_user: root
    vars:
    epic: true
    tasks:
    • name: 修改nginx.conf指定字段
      lineinfile:
      dest=/data/sh/nginx.conf
      regexp="listen 80"
      line="listen 8081;"
      backrefs=yes
      backup=yes
      tags: hanye3
      notify:
      restart nginx
      handlers:
      • name: restart nginx
        service: name = nginx state=reloaded enabled=yes
        上述表示为仅仅修改 listen 80为listen 8081,然后重载nginx
        多任务调用不通的handlers实现:

meta任务的参数值为flush_handlers,"meta: flush_handlers"表示立即执行之前的task所对应handler,什么意思呢?意思就是,在当前meta任务之前,一共有两个任务,task1与task2,它们都有对应的handler,当执行完task1与task2以后,立即执行对应的handler,而不是像默认情况那样在所有任务都执行完毕以后才能执行各个handler

     - hosts: docker
      remote_user: root
      vars:
        epic: true
      tasks:
        - name: gouuradd erp
          group: name=erp gid=1008
          notify: 
          useradd erp
    - meta: flush_handlers
    - name: 修改nginx.conf指定字段
      lineinfile:
    dest=/data/sh/nginx.conf
      regexp="listen 9080"
      line="listen 8081\;"
      backrefs=yes
    backup=yes
     tags: hanye3
    notify:
        restart nginx
handlers:
  - name: restart nginx
    service: name=nginx state=restarted
  - name: useradd erp
    user: name=erp uid=1008 group=erp  password="$6$O9KDopiuPgvkrb4z$ee7/lfljSe79zQLIvDROsFM23hAJRRvVc.JoBWPGW/erp shell=/bin/bash"

调用多个handlers

当我们想要一个task调用多个handler的时候,第一想到的应该是一个handler可以写多个name来实现,但这是行不通的,一个handler只能定义一个handler name,如果想实现调用多个handler,只需要把多个分为一组(listen)

  • name: groupadd erp2
    group: name=erp2 gid=3008
    notify:
    data dir
    • name: copy nginx.conf
      copy: src=/usr/local/nginx/conf/nginx.conf dest=/data/sh/nginx.conf
    • name: 修改nginx.conf指定字段
      lineinfile:
      dest=/data/sh/nginx.conf
      regexp="listen 9080"
      line="listen 8081\;"
      backrefs=yes
      backup=yes
      tags: hanye3
      notify:
      restart nginx
      handlers:
    • name: restart nginx
      service: name=nginx state=restarted
    • name: useradd erp
      user: name=erp uid=1008 group=erp password="$6$O9KDopiuPgvkrb4z$ee7/lfljSe79zQLIvDROsFM23hAJRRvVc.JoBWPGW3WbeHBQVG.IFcg1r8RppAIZ8naxckFGvOX2CIiwY6hEw0" home=/home/erp shell=/bin/bash""
    • name: soft dir
      listen: data dir
      file: path=/data/backup state=directory mode=644
    • name: home dir
      listen: data dir
      file: path=/data/homeerp state=directory mode=644