The following parameters can be used to loop through an array / dictionary / list.
IMPORTANT
When possible, Ansible recommends using the loop parameter, as the loop parameter is meant to supercede the with_items option.
In this example, the loop parameter is used to loop over the food hash.
- name: loop through the 'food' hash
debug:
msg: "{{ item }}"
loop:
- { key: 'fruit', value: 'banana' }
- { key: 'fruit', value: 'orange' }
- { key: 'veggy', value: 'onion' }
- { key: 'veggy', value: 'pepper' }
Which should return the following.
TASK [loop through the 'food' hash]
ok: [server1.example.com] => (item=apple) => {
"msg": {
"key": "fruit",
"value": "apple"
}
}
ok: [server1.example.com] => (item={'key': 'fruit', 'value': 'banana'}) => {
"msg": {
"key": "fruit",
"value": "banana"
}
}
ok: [server1.example.com] => (item={'key': 'veggy', 'value': 'onion'}) => {
"msg": {
"key": "veggy",
"value": "onion"
}
}
ok: [server1.example.com] => (item={'key': 'veggy', 'value': 'pepper'}) => {
"msg": {
"key": "veggy",
"value": "pepper"
}
}
Better yet, the hash can be defined. Here is how you would create a hash of food using the vars plugin.
vars:
food:
- { key: 'fruit', value: 'banana' }
- { key: 'fruit', value: 'orange' }
- { key: 'veggy', value: 'onion' }
- { key: 'veggy', value: 'pepper' }
And then looped through like this.
- name: loop through the 'food' hash
debug:
msg: "{{ item }}"
loop: "{{ food }}"
when parameter
Often, the when parameter is used to only return items in the hash that contain a certain key or value. In this example, only items in the hash that contain the 'fruit' key will be returned.
- name: loop through the 'food' hash
debug:
msg: "{{ item }}"
loop: "{{ food }}"
when: item.key == 'fruit'
Which should return the following. Note that some or all of the output can be suppressed or limited using the no_log or loop_control parameters.
TASK [loop through the 'food' hash]
ok: [server1.example.com] => (item=apple) => {
"msg": {
"key": "fruit",
"value": "apple"
}
}
ok: [server1.example.com] => (item={'key': 'fruit', 'value': 'banana'}) => {
"msg": {
"key": "fruit",
"value": "banana"
}
}
skipping: [server1.example.com] => (item={'key': 'veggy', 'value': 'onion'})
skipping: [server1.example.com] => (item={'key': 'veggy', 'value': 'pepper'})
Accessing keys / values
Here is how you would return the key and value in a loop.
- name: loop through the 'food' hash
debug:
msg: "{{ item.value }} is a {{ item.key }}"
loop: "{{ food }}"
Which should return the following.
TASK [loop through the 'food' hash]
ok: [server1.example.com] => (item={'key': 'fruit', 'value': 'apple'}) => {
"msg": "apple is a fruit"
}
ok: [server1.example.com] => (item={'key': 'fruit', 'value': 'banana'}) => {
"msg": "banana is a fruit"
}
ok: [server1.example.com] => (item={'key': 'veggy', 'value': 'onion'}) => {
"msg": "onion is a veggy"
}
ok: [server1.example.com] => (item={'key': 'veggy', 'value': 'pepper'}) => {
"msg": "pepper is a veggy"
}