Ansible - Loop through list using the with_indexed_items parameter
by
Jeremy Canfield |
Updated: July 06 2023
| Ansible articles
The following parameters can be used to loop through each item in an array / list.
- loop
- vars
- with_items
- with_indexed_items (this article)
- with_list
- with_nested
- with_sequence
In this example, the debug module and with_indexed_items parameter are used to loop over an array and return the index number and value of each item.
---
- hosts: localhost
tasks:
- name: loop through items
debug:
var: item
with_indexed_items:
- apple
- banana
- orange
- grapes
...
Which should return the following.
ok: [localhost] => (item=[0, u'apple']) => {
"ansible_loop_var": "item",
"item": [
0,
"apple"
]
}
ok: [localhost] => (item=[1, u'banana']) => {
"ansible_loop_var": "item",
"item": [
1,
"banana"
]
}
ok: [localhost] => (item=[2, u'orange']) => {
"ansible_loop_var": "item",
"item": [
2,
"orange"
]
}
ok: [localhost] => (item=[3, u'grapes']) => {
"ansible_loop_var": "item",
"item": [
3,
"grapes"
]
}
item.0 can be used to get the index number of each item.
---
- hosts: localhost
tasks:
- name: loop through items
debug:
msg: "{{ item.0 }}"
with_indexed_items:
- apple
- banana
- orange
- grapes
...
Which should return the following
ok: [localhost] => (item=[0, u'apple']) => {
"msg": "0"
}
ok: [localhost] => (item=[1, u'banana']) => {
"msg": "1"
}
ok: [localhost] => (item=[2, u'orange']) => {
"msg": "2"
}
ok: [localhost] => (item=[3, u'grapes']) => {
"msg": "3"
}
item.1 can be used to get the value of each item.
---
- hosts: localhost
tasks:
- name: loop through items
debug:
msg: "{{ item.1 }}"
with_indexed_items:
- apple
- banana
- orange
- grapes
...
Which should return the following.
ok: [localhost] => (item=[0, u'apple']) => {
"msg": "apple"
}
ok: [localhost] => (item=[1, u'banana']) => {
"msg": "banana"
}
ok: [localhost] => (item=[2, u'orange']) => {
"msg": "orange"
}
ok: [localhost] => (item=[3, u'grapes']) => {
"msg": "grapes"
}
Did you find this article helpful?
If so, consider buying me a coffee over at