linux--ansible(playbook3 handlers的多种用法)

本文详细探讨了Ansible Playbook中Handlers的使用,包括如何避免逻辑错误,理解多个tasks调用同一个handler,以及handler的执行顺序。通过示例展示了如何在tasks中间插入handler,以及一个task如何触发多个handler的执行,对于优化自动化运维流程具有指导意义。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给testB安装httpd并启动

在ansible端:

---
- hosts: testB
  remote_user: root
  tasks:
  - name: vim
    lineinfile:
      path=/etc/httpd/conf/httpd.con
      regexp="Listen 80"
      line="Listen 8000"
      backrefs=yes
      backup=yes
  - name: systemctl restart httpd
    service:
      name=httpd
      state=restarted

第一次

在这里插入图片描述
第二次

这个playbook的作用是改变配置文件之后再重启,但是第二次执行并没有改变配置文件还在重启

在这里插入图片描述
为了改变上述问题,引入handlers用法

handlers改变playbook的逻辑错误操作

handlers是个任务列表  相当于另类的tasks
---
- hosts: testB
  remote_user: root
  tasks:
  - name: vim
    lineinfile:
      path=/etc/httpd/conf/httpd.conf
      regexp="Listen 8000"
      line="Listen 80"
      backrefs=yes
      backup=yes
    notify:                          调用handlers
      systemctl restart httpd

  handlers:                          只有tasks改变了 handlers才作用
  - name: systemctl restart httpd
    service:
      name=httpd
      state=restarted

第一次执行

在这里插入图片描述
第二次执行没有逻辑错误

多个handlers被多个tasks中的notify调用

---
- hosts: testB
  remote_user: root
  tasks:
  - name: mkdir chifile1
    file: path=/testdir/chifile1 state=directory
    notify: file1
  - name: mkdir chifile2
    file: path=/testdir/chifile2 state=directory
    notify: file2

  handlers:
  - name: file1
    file: path=/testdir/file1 state=touch
  - name: file2
    file: path=/testdir/file2 state=touch

在这里插入图片描述
在这里插入图片描述

如果在testB上删除file1 fiel2 再执行命令file1 file2不会再创建

tasks不执行 handlers不会执行
在这里插入图片描述

handlers执行顺序等于定义顺序

先执行完tasks 再按照先后顺序执行handlers

tasks执行中间插入handlers

---
- hosts: testB
  remote_user: root
  tasks:
  - name: task1
    file: path=/testdir/chifile1 state=directory
    notify: handlers1
  - name: task2
    file: path=/testdir/chifile2 state=directory
    notify: handlers2
  - meta: flush_handlers            执行之前调用的handlers

  - name: task3
    file: path=/testdir/chifile3 state=directory
    notify: handlers3

  handlers:
  - name: handlers1
    file: path=/testdir/file1 state=touch
  - name: handlers2
    file: path=/testdir/file2 state=touch
  - name: handlers3
    file: path=/testdir/file3 state=touch

在这里插入图片描述

一个tasks调用多个handlers

---
- hosts: testB
  remote_user: root
  tasks:
  - name: task1
    file: path=/testdir/test1 state=touch
    notify: handler group                 调用组

  handlers:
  - name: handlers1
    listen: handler group                 强调组
    file: path=/testdir/file1 state=touch
  - name: handlers2
    listen: handler group                 强调组
    file: path=/testdir/file2 state=touch

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值