给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