The following parameters can be used to loop through each item in an array / list.
- loop
- vars
- with_items
- with_indexed_items
- with_list (this article)
- with_nested
- with_sequence
The with_list parameter is equivelant to the loop parameter, and can be used interchangeably. In this example, the debug module and with_list parameter are used to loop over an array of fruit (a fruit loop!). Notice the double curley braces {{ ... }}. Jinja2 uses double curley braces for variables.
The loop parameters will, by default, use the {{ item }} variable for each item in the list. Or, the loop_control parameter with loop_var can be used to define your own variable for each item in the list.
- name: "loop through the 'fruit' array"
debug:
msg: "{{ item }}"
with_list:
- apple
- banana
- orange
- grapes
The loop parameter could be used instead of the with_list parameter.
- name: "loop through the 'fruit' array"
debug:
msg: "{{ item }}"
loop:
- apple
- banana
- orange
- grapes
Regardless of whether the loop or with_list parameter are used, the following should be returned.
TASK [loop through the 'fruit' array]
ok: [server1.example.com] => (item=apple) => {
"msg": "apple"
}
ok: [server1.example.com] => (item=banana) => {
"msg": "banana"
}
ok: [server1.example.com] => (item=orange) => {
"msg": "orange"
}
ok: [server1.example.com] => (item=grapes) => {
"msg": "grapes"
}
SInce the loop parameter is preferred over the with_list parameter, refer to Ansible - loop parameter.
Did you find this article helpful?
If so, consider buying me a coffee over at