Ansible:执行具有特定标签的角色



面临一个与角色中的标签相关的问题。 我已经指定了一个要运行的标签(create(,其他标签应该跳过,但是两个标签都在执行,有人可以解释如何解决这个问题吗?
roles_main.yml

---
- name: roles
hosts: "{{ host }}"
#  hosts: localhost
gather_facts: False
become: yes
tasks:
- import_role:
name: "{{ role_name }}"
tags: "{{ tag_name }}"

Linux/main.yml

---
- name: in file
import_tasks: in.yml
tags: create
delegate_to: localhost
- name: out file
import_tasks: out.yml
tags: get
delegate_to: localhost 
ansible-playbook roles_main.yml -e host=localhost -e ritm_ticket=test1 -e role_name=linux -e tag_name=create -v

您需要添加参数"--tags"(或--skip-tags(来指定要运行的标签,即:

ansible-playbook roles_main.yml -e host=localhost -e ritm_ticket=test1 -e role_name=linux -e tag_name=create -v --tags=create

欲了解更多信息:

https://docs.ansible.com/ansible/latest/user_guide/playbooks_tags.html

标签有 3 个特殊关键字:

已标记
  • :仅运行已标记的任务。
  • 未标记
  • :仅运行未标记的任务。
  • 全部:运行所有任务。

默认情况下,Ansible 的运行就像 --tag 都已指定一样。

您不会传递任何标签作为参数,因此 ansible 使用 --tag all 运行并执行所有任务并导入 in.yml 和 out.yml。

如果你想使用ansible的标签功能,你可以传递--tags或--skip-tags参数。 由于您的播放依赖于变量的值,因此另一种解决方案可以是使用 Conditionals 语句。

您可以将脚本更改为:

roles_main.yml

---
- name: roles
hosts: "{{ host }}"
#  hosts: localhost
gather_facts: False
become: yes
tasks:
- import_role:
name: "{{ role_name }}"
when: tag_name == "create"

Linux/main.yml

---
- name: in file
import_tasks: in.yml
when: tag_name == "create"
delegate_to: localhost
- name: out file
import_tasks: out.yml
when: tag_name == "get"
delegate_to: localhost 

这应该行得通。

祝你好运!

最新更新