Today, I will continue to introduce Linux operation and maintenance related knowledge. The main content of this article is the Tag and Handler in Ansible.
1. Definition and invocation of Tag in Ansible
In Ansible, when writing a Playbook, it is supported to define one or more Tag tags for tasks. When executing a Playbook, we can use the -t parameter to determine what task to execute according to the Tag. A playbook with tags looks like this:
---
- 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
In the above configuration, we define httpd and nginx labels for the three tasks respectively, so that when we call the Playbook, we can specify the tasks to be executed according to the labels. Join us to execute the installation of Apache, you can execute the command:
ansible-playbook tag.yml -t httpd
In this way, all tasks with httpd tags in the Playbook will be executed, and tasks without httpd tags will not be executed. The execution results of the above commands are as follows:
Second, the definition and call of Handler in Ansible
Ansible's Playbook also supports the use of Handler. The so-called Handler is a special task, which is always executed after all tasks are executed. An example of a Playbook with Handler in Ansible is as follows:
---
- 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
In the Playbook, after the Config Apache instruction, there is a notify, which indicates the function of calling Ansible Handler, and there is a handler module behind the Playbook'. In this module, the Handler of Restart Apache is defined and configured later. The Handler should perform a hit operation. In this way, after all tasks are executed, the Handler will be executed.
The execution result of the Playbook is as follows: It can be
seen that the role of Ansible's Handler.
Originality is not easy, please indicate the source for reprinting: https://blog.csdn.net/weixin_40228200