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?
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 .
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.
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.
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.
Now supported as of Ansible 2.3.0:
- name: myrole with_items: - "aone" - "atwo" include_role: name: myrole vars: thing: "{{ item }}"
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 }}" }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With