I have a json file that contains a list of dictionaries:
$ cat test.json
[
{
"key1": "val1"
},
{
"key2": "val2"
},
{
"key3": "val3"
}
]
I would like to iterate over the list and print the key and value in each dict object but can't figure out a way to do so.
- hosts: localhost
gather_facts: no
tasks:
- set_fact:
mylst: "{{ lookup('file', '/home/ansible/test.json') | from_json }}"
- debug:
msg: "One dict is {{ item }}"
with_items: "{{ mylst }}"
- debug:
msg: "Key/values are {{ item.key }} and {{item.value }}"
with_items: "{{ mylst }}"
$ ansible-playbook run.yml
PLAY [localhost] *****************************************************************************
TASK [set_fact] ******************************************************************************
ok: [localhost]
TASK [debug] *********************************************************************************
ok: [localhost] => (item={u'key1': u'val1'}) => {
"msg": "One dict is {u'key1': u'val1'}"
}
ok: [localhost] => (item={u'key2': u'val2'}) => {
"msg": "One dict is {u'key2': u'val2'}"
}
ok: [localhost] => (item={u'key3': u'val3'}) => {
"msg": "One dict is {u'key3': u'val3'}"
}
TASK [debug] *********************************************************************************
fatal: [localhost]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'key'\n\nThe error appears to be in '/home/ansible/run.yml': line 11, column 5, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n - debug:\n ^ here\n"}
PLAY RECAP ***********************************************************************************
localhost : ok=2 changed=0 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0