Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ansible

Is it possible to call a role multiple times in a loop like this:

vars:   my_array:     - foo     - bar     - baz  roles:   - role: foobar     with_items: my_array 

How can we do this?

like image 689
hewo Avatar asked Oct 29 '15 13:10

hewo


People also ask

What is {{ item }} Ansible?

item is not a command, but a variable automatically created and populated by Ansible in tasks which use loops. In the following example: - debug: msg: "{{ item }}" with_items: - first - second. the task will be run twice: first time with the variable item set to first , the second time with second .

How do you do nested loops in Ansible?

Nested loops in many ways are similar in nature to a set of arrays that would be iterated over using the with_nested operator. Nested loops provide us with a succinct way of iterating over multiple lists within a single task. Now we can create nested loops using with_nested.

Can Ansible roles be reused by playbooks in a different directory?

You can re-use tightly focused playbooks, but you can only re-use them statically, not dynamically. A role contains a set of related tasks, variables, defaults, handlers, and even modules or other plugins in a defined file-tree.

Which loop can be used to iterate over files in a directory Ansible?

Introduction to Ansible Loop. Ansible loop is used to repeat any task or a part of code multiple times in an Ansible-playbook. It includes the creation of multiple users using the user module, installing multiple packages using apt or yum module or changing permissions on several files or folders using the file module.


2 Answers

Now supported as of Ansible 2.3.0:

- name: myrole   with_items:     - "aone"     - "atwo"   include_role:     name: myrole   vars:     thing: "{{ item }}" 
like image 152
ritzk Avatar answered Oct 10 '22 06:10

ritzk


There's no way to loop over a role currently but as mentioned in that Google Group discussion you can pass a list or dict to the role and then loop through that internally.

So instead you could do something like:

# loop_role/tasks/main.yml  - name: debug item   debug: var="{{ item }}"   with_items: my_array 

And then use it like this:

- hosts: all   vars:     my_array:       - foo       - bar       - baz    roles:     - { role: loop_role, my_array: "{{ my_array }}" } 
like image 24
ydaetskcoR Avatar answered Oct 10 '22 04:10

ydaetskcoR