【问题标题】:Run tasks with a certain tag within role in Ansible在 Ansible 中的角色内运行具有特定标签的任务
【发布时间】:2019-12-16 08:22:50
【问题描述】:

我有以下文件夹结构,灵感来自 Ansibles 文档中的最佳实践部分:

my-playbook.yml
my-role
   |
   |── tasks
         |
         |── my-task.yml

我已在属于角色的 my-task.yml 文件中标记了任务。我使用 ansible-playbook.yml --tags "mytag" 执行剧本。不幸的是,所有任务都被跳过。我可以只在剧本中直接过滤任务吗?

在我的剧本中,我做了类似的事情

- hosts: ansible_server
  connection: local
  gather_facts: no
  roles:
   - validate_properties

提前致谢!

【问题讨论】:

  • 您需要在 main.yml 中包含任务,因为这是角色执行期间调用的默认文件。

标签: ansible tags roles


【解决方案1】:

您应该做的是使用include_role 模块从task 调用role。在task 上,您可以申请tags。以这个playbook为例:

---
- name: Tag role test
  hosts: local
  connection: local
  gather_facts: no
  tasks:
    - include_role:
        name: debug
      tags:
        - dont_run

    - debug:
        msg: Solo shot first
      tags:
        - run

我的role/debug 仅包含一个打印Hello, world! 的任务。

如果你直接调用这个playbook,你会得到这个输出:

PLAY [Tag role test]

TASK [debug : debug] 
ok: [localhost] =>
  msg: Hello, world!

TASK [debug] 
ok: [localhost] =>
  msg: Solo shot first

PLAY RECAP
localhost                  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

但是,如果您像这样排除 dont_run 任务:

ansible-playbook tag_roles.yml --skip-tags dont_run

这是输出:

PLAY [Diff test] 

TASK [debug] 
ok: [localhost] =>
  msg: Solo shot first

PLAY RECAP 
localhost                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

希望对你有帮助。

【讨论】:

    【解决方案2】:

    您还必须使用您想要运行的标签来标记子任务: 主要任务:

    - name: "test tags on sub task"
      include_tasks: subtask.yml
      with_items: "{{ myList }}"
      loop_control:
        label: item
      tags: test
    
    

    子任务:

    debug: msg="Sub Task"
    tags: test
    

    【讨论】:

      猜你喜欢
      • 2020-10-05
      • 2018-03-29
      • 2017-02-12
      • 2021-07-12
      • 1970-01-01
      • 2017-08-02
      • 1970-01-01
      • 2019-01-14
      • 2018-10-06
      相关资源
      最近更新 更多