0

I need to somehow loop over a list of variables and execute both of the below roles once for each iteration, on each iteration passing a variable to the role. For example, given a variable list of 100-101, I need to execute in the order role1:100, role2:100, role1:101, role2:101. The variables 100-100 should be passed to the tasks inside the role.

---
- hosts: group1
  tasks:
  - include_role:
      name: role1

- hosts: group2
  tasks:
  - include_role:
      name: role2

I was looking at the below answer as a possible solution but I am not sure how to adapt it to my needs. Can the above scenario be accomplished in Ansible?

Ansible: How to iterate over a role with an array?

Matt
  • 13
  • 4

1 Answers1

0

Loop over the Cartesian product of variables and role names:

vars:
  roles_to_include:
    - role1
    - role2
  values_to_pass:
    - 100
    - 101

tasks:
  - include_role:
      name: "{{ item.1 }}"
    vars:
      my_variable: "{{ item.0 }}"
    loop: "{{ values_to_pass | product(roles_to_include) | list }}"
techraf
  • 64,883
  • 27
  • 193
  • 198
  • Thanks, this executes the roles in the required order. Another requirement is that role1 needs to run on one set of hosts (group1) and role2 on a separate group of hosts (group2). So far I have been able to get the above working with a single host group, how can it be adapted to run each role on a separate group of hosts? – Matt Aug 02 '18 at 18:19
  • I was able to accomplish what I had asked in the above comment by adding a conditional to the tasks inside each role like this: when: "'group1' in group_names". – Matt Aug 02 '18 at 20:49