自动化运维—简单的playbook(handler模块&meta模块)
文章目录
playbook1 简单管理http服务
修改服务端口并重启服务
首先在远程主机中确保有该服务:
yum install httpd -y
systemctl start httpd
查看端口:
netstat -antlp | grep httpd
修改服务端口80为8888并重启:
vim httpd.yml
---
- hosts: testB
remote_user: root
tasks:
- name: Modify the configuration
lineinfile:
path=/etc/httpd/conf/httpd.conf
regexp="Listen 80"
line="Listen 8888"
backrefs=yes
backup=yes
- name: restart httpd
service:
name=httpd
state=restarted
执行:
ansible-playbook httpd.yml
查看端口改为8888:
netstat -antlp | grep httpd
playbook2
在次执行上一个脚本时,我们会发现它虽然没有改变端口(上一步改过了,根据幂等性不会改变),但服务被重启了,这显然是不符合常理的。如何写一个playbook时它在做改变端口这一动作后才重启,若没改变则不重启?
调用handler模块:
vim httpd1.yml
---
- hosts: testB
remote_user: root
tasks:
- name: Modify the configuration
lineinfile:
path=/etc/httpd/conf/httpd.conf
regexp="Listen 80"
line="Listen 8888"
backrefs=yes
backup=yes
notify:
restart httpd
handlers:
- name: restart httpd
service:
name=httpd
state=restarted
这次执行时服务就不会重启了
playbook3
通过这个实验更清楚的了解handler模块的用法:
首先在远程主机中清空/testdir下的内容(方便查看效果,之前没有做过可忽略):
cd /testdir
rm -fr *
vim mkdir.yml
---
- hosts: testB
remote_user: root
tasks:
- name: make file1
file:
path=/testdir/file1
state=directory
notify: h1
- name: make file2
file:
path=/testdir/file2
state=directory
notify: h2
handlers:
- name: h1
file:
path=/testdir/h1
state=touch
- name: h2
file:
path=/testdir/h2
state=touch
notify用来调用handlers中的任务,表示如果执行tasks中的动作才会执行调用的handlers动作
执行第一遍:
ansible-playbook mkdir.yml
所有动作都执行了
执行第二遍:
ansible-playbook mkdir.yml
没有执行任何动作
在远程主机中删除h1 h2,再次执行:
仍然不会执行任何动作,因为tasks中的内容没有执行
如果此时把notify: h1改为h2,而下面的h2改为h1,删除/testdir下的所有文件后再次执行,会发现顺序还是先执行h1再执行h2,这是因为handler任务的执行顺序与调用顺序无关,而与handlers:下写的顺序有关
playbook4
我们会发现上一个脚本是将所有task任务执行完,才去执行handler中的任务。那么如果想在执行完一个task就立即执行它调用的handler,然后再去执行task中的其他任务,就需要使用meta模块
首先在远程主机中清空/testdir下的内容(方便查看效果,之前没有做过可忽略):
cd /testdir
rm -fr *
vim mkdir1.yml
---
- hosts: testB
remote_user: root
tasks:
- name: task1
file:
path=/testdir/file1
state=directory
notify: handler1
- meta: flush_handlers
- name: task2
file:
path=/testdir/file2
state=directory
notify: handler2
- meta: flush_handlers
- name: task3
file:
path=/testdir/file3
state=directory
notify: handler3
handlers:
- name: handler1
file:
path=/testdir/h1
state=touch
- name: handler2
file:
path=/testdir/h2
state=touch
- name: handler3
file:
path=/testdir/h3
state=touch
执行:
ansible-playbook mkdir1.yml
可以看到执行顺序为task1—handler1—task2—handler2—task3—handler3
playbook5
如果想执行一个task任务而调用多个handler,就需要给他们起一个共同的名字来调用:
首先在远程主机中清空/testdir下的内容
vim mkdir2.yml
---
- hosts: testB
remote_user: root
tasks:
- name: task1
file:
path=/testdir/testfile
state=directory
notify: handler group1
handlers:
- name: h1
listen: handler group1
file:
path=/testdir/h1
state=touch
- name: h2
listen: handler group1
file:
path=/testdir/h2
state=touch
listen:andler group1表示共同名为handler group1,而调用时调用这个名字就会同时调用所有设定为handler group1的handler任务
执行:
ansible-playbook mkdir2.yml
可以看到task1执行完后分别执行了h1和h2