There will inevitably be scenarios where you are looping through JSON or a dictionary that contains many, many key value pairs. The output can be vast, making it difficult to display only the data you care about.
Fortunately, no_log or loop_control and label can be used to suppress output.
For example, let's say vars is used to define the "food" dictionary and debug is used to loop through the "food" dictionary.
---
- hosts: localhost
vars:
food:
- { key: 'fruit', value: 'banana' }
- { key: 'fruit', value: 'orange' }
- { key: 'veggy', value: 'onion' }
- { key: 'veggy', value: 'pepper' }
tasks:
- debug:
msg: "{{ item.value }}"
with_items: "{{ food }}"
...
Which should return the following. Imagine this was instead of dictionary with thousands of key value pairs!
ok: [localhost] => (item={u'value': u'apple', u'key': u'fruit'}) => {
"msg": "apple"
}
ok: [localhost] => (item={u'value': u'banana', u'key': u'fruit'}) => {
"msg": "banana"
}
ok: [localhost] => (item={u'value': u'onion', u'key': u'veggy'}) => {
"msg": "onion"
}
ok: [localhost] => (item={u'value': u'pepper', u'key': u'veggy'}) => {
"msg": "pepper"
}
no_log can be used to suppress the output.
---
- hosts: localhost
vars:
food:
- { key: 'fruit', value: 'banana' }
- { key: 'fruit', value: 'orange' }
- { key: 'veggy', value: 'onion' }
- { key: 'veggy', value: 'pepper' }
tasks:
- debug:
msg: "{{ item.value }}"
with_items: "{{ food }}"
no_log: true
...
Which should return the following. However, I almost never use no_log because then it will be impossible to debug since "None" will be returned.
ok: [localhost] => (item=None)
ok: [localhost] => (item=None)
ok: [localhost] => (item=None)
ok: [localhost] => (item=None)
loop_control and label can be used to limit the output to only the item being parsed.
---
- hosts: localhost
vars:
food:
- { key: 'fruit', value: 'apple' }
- { key: 'fruit', value: 'banana' }
- { key: 'veggy', value: 'onion' }
- { key: 'veggy', value: 'pepper' }
tasks:
- debug:
msg: "{{ item.value }}"
with_items: "{{ food }}"
loop_control:
label: "{{ item.value }}"
...
Which should return the following. Now you still get some valuable data being returned that can assist when debugging.
ok: [localhost] => (item=apple) => {
"msg": "apple"
}
ok: [localhost] => (item=banana) => {
"msg": "banana"
}
ok: [localhost] => (item=onion) => {
"msg": "onion"
}
ok: [localhost] => (item=pepper) => {
"msg": "pepper"
}
Did you find this article helpful?
If so, consider buying me a coffee over at