ansible使用12--handler

修改nginx的配置文件,某个server的端口从8080改成8088,修改配置后重启nginx(尽管nginx读入新配置可用nginx -s reload,但这里作为示例执行重启)。剧本如下:

---
- hosts: self1-1
  remote_user: root
  tasks:
  - name: Modify the configuration
    lineinfile:
      path=/etc/nginx/conf.d/test.zsythink.net.conf
      regexp="listen(.*) 8080 (.*)"
      line="listen\1 8088 \2"
      backrefs=yes
      backup=yes
  - name: restart nginx
    service:
      name=nginx
      state=restarted

这两个任务是彼此分离的,如果第一个任务没有执行(比如执行两遍剧本,第二遍由于幂等性,修改配置的任务不会执行),第二个任务依旧会执行。使用handlers做到如果第一个任务没有执行更改那么第二个任务也不会执行。

---
- hosts: self1-1
  remote_user: root
  tasks:
  - name: Modify the configuration
    lineinfile:
      path=/etc/nginx/conf.d/test.zsythink.net.conf
      regexp="listen(.*) 8080(.*)"
      line="listen\1 8088\2"
      backrefs=yes
      backup=yes
    notify:
      restart nginx
 
  handlers:
  - name: restart nginx
    service:
      name=nginx
      state=restarted

这个示例中,任务restart nginx被Modify the configuration任务所调用,使用了notify关键字。
所以,只有Modify任务真正做了修改,changed=true即黄色返回时,restart任务才会执行。

tasks中有多个任务,handler也是一个任务列表,tasks中的任务可以调用handler中不同的任务

---
- hosts: self1-1
  remote_user: root
  tasks:
  - name: make testfile1
    file: path=/testdir/testfile1
          state=directory
    notify: ht2
  - name: make testfile2
    file: path=/testdir/testfile2
          state=directory
    notify: ht1
 
  handlers:
  - name: ht1
    file: path=/testdir/ht1
          state=touch
  - name: ht2
    file: path=/testdir/ht2
          state=touch

handle执行的顺序与notify的顺序无关,仅按照playbook中handles的任务顺序执行,如果需要执行某个tasks任务后立即执行handles任务,那么使用meta模块

---
- hosts: self1-1
  remote_user: root
  tasks:
  - name: task1
    file: path=/testdir/testfile
          state=touch
    notify: handler1
  - name: task2
    file: path=/testdir/testfile2
          state=touch
    notify: handler2
 
  - meta: flush_handlers
 
  - name: task3
    file: path=/testdir/testfile3
          state=touch
    notify: handler3
 
  handlers:
  - name: handler1
    file: path=/testdir/ht1
          state=touch
  - name: handler2
    file: path=/testdir/ht2
          state=touch
  - name: handler3
    file: path=/testdir/ht3
          state=touch

meta: flush_handler表示立即执行之前的task所对应的handle。示例中task1,task2执行过后,立即执行handler1,handler2,后面才执行task3

task中如何一次性调用多个handler,使用listen,通过把handler分组实现

---
- hosts: test70
  remote_user: root
  tasks:
  - name: task1
    file: path=/testdir/testfile
          state=touch
    notify: handler group1
 
  handlers:
  - name: handler1
    listen: handler group1
    file: path=/testdir/ht1
          state=touch
  - name: handler2
    listen: handler group1
    file: path=/testdir/ht2
          state=touch

handler1,2都被编入group1.一起被调用

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值