In this example, the vars plugin is used to define the "food" hash.
vars:
food:
- { key: 'fruit', value: 'banana' }
- { key: 'fruit', value: 'orange' }
- { key: 'veggy', value: 'onion' }
- { key: 'veggy', value: 'pepper' }
Let's say you are using the set_fact module to define the "foo" variable, the with_items parameter to loop through the hash, and the when parameter only return items in the hash that contain a certain key or value. In this example, the "foo" variable should contain a value of "apple".
- name: set_fact to apple
set_fact:
foo: "{{ item.value }}"
with_items: "{{ food }}"
when:
- item.key == 'fruit'
- item.value == 'apple'
Which should return the following. Notice the skipping lines are showing the keys and values.
TASK [set fact to apple]
ok: [server1.example.com] => (item=apple) => {
"msg": {
"key": "fruit",
"value": "apple"
}
}
skipping: [server1.example.com] => (item={'key': 'fruit', 'value': 'banana'})
skipping: [server1.example.com] => (item={'key': 'veggy', 'value': 'onion'})
skipping: [server1.example.com] => (item={'key': 'veggy', 'value': 'pepper'})
If you would like to suppress the output, the no_log: true parameter can be used.
- name: set fact to apple
set_fact:
foo: "{{ item.value }}"
with_items: "{{ food }}"
when:
- item.key == 'fruit'
- item.value == 'apple'
no_log: true
Which should return the following. However, this will make it difficult to debug, since "None" will be returned.
TASK [set fact to apple]
ok: [server1.example.com] => (item=None)
skipping: [server1.example.com] => (item=None)
skipping: [server1.example.com] => (item=None)
skipping: [server1.example.com] => (item=None)
The loop_control parameter can be used to limit the output to only the item being parsed.
- name: set fact to apple
set_fact:
foo: "{{ item.value }}"
with_items: "{{ food }}"
loop_control:
label: "{{ item.value }}"
when:
- item.key == 'fruit'
- item.value == 'apple'
Which should return the following. Now you still get some valuable data being returned that can assist when debugging.
TASK [set fact to apple]
ok: [server1.example.com] => (item=apple)
skipping: [server1.example.com] => (item=banana)
skipping: [server1.example.com] => (item=onion)
skipping: [server1.example.com] => (item=pepper)