首页 > 其他分享 >Ansible通知与处理机制

Ansible通知与处理机制

时间:2022-11-19 15:55:29浏览次数:48  
标签:tmp file1 handlers 通知 create dir1 Ansible notify 机制

一、Ansible通知与处理机制介绍
notify键值对(通知)与handlers键值对(处理)
当任务模块执行完毕后,任务的notifiy键值对将观察任务模块的执行是否对被管理主机进行了修改,并根据返回结果决定是否通知handlers来处理
1)任务返回结果为changed——模块修改了被管理主机
notify将通知handlers键值对进行处理

2)任务返回结果为ok——模块没有修改被管理主机
notify不会通知hanlders关键字,handlers中定义的操作将不会被执行

注:notify + handlers提供了一种条件机制,能够根据前面任务的执行情况,实现后续操作的有条件执行

二、Ansible通知与处理的实现
1、notify键值对
notify键值对在task任务中定义,描述了该任务会产生什么通知
eg:

- hosts:  group1
     tasks:
        - name: copy file
          copy: src=copy.txt  dest=/tmp
          notify: 产生的通知名字

2、handlers键值对
handlers在play中定义,一个play只有一个handlers
与tasks键值对类似,handlers键值对包含了一个任务列表(其中任务又称为handler任务)
当收到notify通知时,handlers会选择对应的任务进行执行
eg:

   handlers:
         
        - 任务1
        - 任务2
          ......
        - 任务N

3、notify与handlers

当通知发生时,notify会将notify通知的名字 与 handler任务的名字(name)进行匹配,从而知道执行哪一个任务
eg:

---
- hosts:  group1
     tasks:
        - name: create dir
          file: path=/tmp/dir1 state=directory
          notify: create file1
     handlers:
        - name: create file1
          file: path=/tmp/dir1/file1 state=touch
        - name: create file2
          file: path=/tmp/dir1/file2 state=touch
#在被管理主机上新建/tmp/dir1目录
#如果新建成功,则在/tmp/dir1文件夹下创建文件file1
#如果/tmp/dir1文件夹已存在,则不创建文件file1

三、Ansible通知与处理的执行

1、handle任务的执行
一个play只有一个handlers, 一个handler任务,最多只会被执行一次
所有task任务都执行完毕后,才会执行handler任务
当有多个handler任务需要执行时,将按照handler任务在任务列表中的顺序依次执行

---
- hosts: gorup1
  tasks:
     - name: create dir1
       file: path=/tmp/dir1 state=directory
       notify: create file1
     - name: create dir2 
       file: path=/tmp/dir2 state=directory
       notify: create file1
 headlers:
      - name: create file1
        file: path=/tmp/file1 state=touch

#创建dir1和dir2都会触发创建file1,但是由于一个headler只会执行一次
#因此只有dir1任务会创建file1,而dir2任务不会创建file1

2、notify的执行
一个notify键值对,可以同时产生多个通知

---
- hosts: gorup1
  tasks:
     - name: create dir1
       file: path=/tmp/dir1 state=directory
       notify: 
        - create file1
        - create file2
  
 headlers:
      - name: create file1
        file: path=/tmp/dir1/file1 state=touch
      - name: create file2
        file: path=/tmp/dir1/file2 state=touch
#当创建dir1后会notity会通知headlers执行notify列表的两个任务,即在/tmp/dir1/下创建出两个file1和file2两个文件

标签:tmp,file1,handlers,通知,create,dir1,Ansible,notify,机制
From: https://www.cnblogs.com/tjane/p/16906270.html

相关文章