作用
你写了一个很长的playbook,其中有很多的任务,这并没有什么问题,不过在实际使用这个剧本时,你可能只是想要执行其中的一部分任务而已,或者,你只想要执行其中一类任务而已,而并非想要执行整个剧本中的全部任务,这个时候我们该怎么办呢?我们可以借助tags实现这个需求。
案例
[root@master ~]# vi hosts.yaml
- hosts: server1
remote_user: root
tasks:
- name: copy hosts01
copy: src=/etc/hosts01 dest=/opt/hosts
tags: # 第一个任务打上标签 aaa
- aaa
- name: touch hosts02
file: path=/opt/hosts state=touch
[root@master ~]# ansible-playbook hosts.yaml --tags="aaa"
# 执行任务调用 aaa 标签,只会执行第一个任务,后面第二个任务不会执行
验证
[root@node1 ~]# cd /opt/
[root@node1 opt]# ll
总用量 2
-rw-r--r--. 1 root root 158 1月 10 19:36 hosts
只执行了打上标签的任务
再次在后面添加一个任务,并打上相同的标签
[root@master ~]# vi hosts.yaml
- hosts: server1
remote_user: root
tasks:
- name: copy hosts01
copy: src=/etc/hosts dest=/opt/hosts
tags:
- aaa
- name: touch hosts02
file: path=/opt/hosts02 state=touch
- name: mkdir directory
file: path=/opt/hosts03 state=directory
tags:
- aaa
[root@master ~]# ansible-playbook hosts.yaml --tags="aaa"
# 依旧执行任务调用 aaa 标签
验证
[root@node1 ~]# cd /opt/
[root@node1 opt]# ll
总用量 4
-rw-r--r--. 1 root root 158 1月 10 19:36 hosts
drwxr-xr-x. 2 root root 6 1月 10 19:36 hosts03
执行了打上相同标签的任务