Ansible详解(十三)——Ansible中的Tag和Handler

今天继续给大家介绍Linux运维相关知识,本文主要内容是Ansible中的Tag和Handler。

一、Ansible中Tag的定义和调用

在Ansible中,编写Playbook时,支持给task定义一个或多个Tag标签,我们在执行Playbook时,可以使用-t参数,根据Tag来确定具体执行什么任务。一个带有Tag的playbook如下所示:

---
- hosts: exp
  remote_user: root
  tasks:
  - name: Install Apache
    yum: name=httpd state=installed
    tags: httpd
  - name: Install Nginx
    yum: name=nginx state=installed
    tags: nginx
  - name: Stop firewalld & iptables & selinux
    shell: systemctl stop firewalld ; iptables -F ; setenforce 0
    tags:
    - httpd
    - nginx

在上述配置中,我们给三个tasks分别定义了httpd和nginx两种标签,这样,我们在调用该Playbook时,就可以根据标签来明确要执行的task了。加入我们要执行安装Apache,则可以执行命令:

ansible-playbook tag.yml -t httpd

这样,在该Playbook中所有含有httpd标签的task机会执行,而不含有httpd标签的task就不会执行,上述命令执行结果如下:
在这里插入图片描述

二、Ansible中Handler的定义和调用

Ansible的Playbook还支持使用Handler,所谓Handler,就是一种特殊的task,这种task总是在所有的task执行完成后再执行。Ansible中带有Handler的Playbook示例如下:

---
- hosts: exp
  remote_user: root
  tasks:
  - name: Install Apache
    yum: name=httpd state=installed
  - name: Config Apache
    copy: src=httpd.conf dest=/etc/httpd/httpd.cong
    notify: Restart Apache
  - name: Stop firewalld
    shell: systemctl stop firewalld;iptables -F;setenforce 0;
  handlers:
  - name: Restart Apache
    service: name=httpd state=restarted

在该Playbook中,在Config Apache指令的后面,有一个notify,表示调用Ansible Handler的作用,在该Playbook’的后面有一个handler模块,在该模块中,定义了Restart Apache的Handler,并且在后面配置了该Handler应当进行打操作。这样,在所有的Task执行完毕后,就会执行该Handler。
该Playbook执行结果如下:
在这里插入图片描述
由此可见,Ansible的Handler的作用。
原创不易,转载请说明出处:https://blog.csdn.net/weixin_40228200

猜你喜欢

转载自blog.csdn.net/weixin_40228200/article/details/123554734