首页 > 解决方案 > How to run tasks for roles I would select with limit?

问题描述

In my playbook I have:

roles:
  - role: role_1
  - role: role_2

In my roles directory structure I have defined vars with different values under role_1 and role_2

When invoking the playbook, I am trying to ask it to only consider the role I am interested in at the moment, by using limit:

ansible-playbook -i ./hosts.yml  myplaybook.yml --limit role_1

What I expect: It will disregard the variable values under role_2, because I asked it to limit to role_1 What I get: role_2 variables values override role_1, because role_2 is lexicographically later. ugh!

What else I tried: I tried to use tags:

roles:
  - role: role_1
    tags: [ role_1_tag ]
  - role: role_2
    tags: [ role_2_tag ]

Result is still the undesired

Edit: After following the first answer

The syntax for include_role as given here (and in the documentation) does not work without modifications. In the end I made this:

tasks:
  - name: include role_1
    include_role:
      name: role1
      apply:
        tags:
          - role_1_tag
    tags: always

  - name: include role_2
    include_role:
      name: role_2
      apply:
        tags:
          - role_2_tag
    tags: always

But even then, When I run it, nothing is executed. I run it like this:

ansible-playbook -i ./hosts.yml % --limit role_1 -t role_1_tag

Trying another way:

tags: always
tasks:
  - name: include role_1
    include_role:
      name: role1
      apply:
        tags:
          - role_1_tag


  - name: include role_2
    include_role:
      name: role_2
      apply:
        tags:
          - role_2_tag

Ansible tries to proceed with the other tasks, but without accessing any of the vars under the role, resulting in variable not found error

Since I put the tags: outside of tasks I guessed the tags need to be mentioned for every task. Even doing that, I got the same result, which is:

fatal: [host_group]: FAILED! => {"msg": "'my_vars' is undefined"}

Edit2: Using public: yes seems to get Ansible to read the vars, however, again, it reads them all, and --limit has no effect

标签: ansibleansible-role

解决方案


Q:“只考虑我目前感兴趣的角色。”

答:使用include_role。例如

- include_role:
    name: role_1
- include_role:
    name: role_2

默认情况下,参数publicno

此选项指示角色的 vars 和默认值是否暴露给 playbook。如果设置为 yes,则变量将可用于 include_role 任务之后的任务。此功能不同于角色标题或 import_role 下列出的角色的标准变量公开,因为它们在 playbook 解析时公开,并且也可用于早期的角色和任务。


笔记


推荐阅读