Ansible nested Dictionary parsing

How to Parse deeply nested dictionary in Ansible to get key / value pair that is all nested inside ?

My dictionary output:

parser_output": {
“changed”: false,
“failed”: false,
“parsed”: {
“isis”: {
“2”: {
“vrf”: {
“default”: {
“interfaces”: {
“FH0/0/0/0”: {
“neighbors”: {
“B6”: {
“holdtime”: “24”,
“ietf_nsf”: “Unable”,
“snpa”: “PtoP”,
“state”: “Up”,
“type”: “L1”
}
}
},
“FH0/0/0/1”: {
“neighbors”: {
“BF0”: {
“holdtime”: “28”,
“ietf_nsf”: “Capable”,
“snpa”: “PtoP”,
“state”: “Up”,
“type”: “L1”
}
}
},
“FH0/0/0/2”: {
“neighbors”: {
“B8”: {
“holdtime”: “28”,
“ietf_nsf”: “Capable”,
“snpa”: “PtoP”,
“state”: “Up”,
“type”: “L1”
}
}
},
“FH0/1/0/1”: {
“neighbors”: {
“BF1”: {
“holdtime”: “25”,
“ietf_nsf”: “Capable”,
“snpa”: “PtoP”,
“state”: “Up”,
“type”: “L1”
}
}
},
“FH0/1/0/2”: {
“neighbors”: {
“B8”: {
“holdtime”: “22”,
“ietf_nsf”: “Capable”,
“snpa”: “PtoP”,
“state”: “Up”,
“type”: “L1”
}
}
},
“HundredGigE0/0/0/23/0”: {
“neighbors”: {
“BU0”: {
“holdtime”: “22”,
“ietf_nsf”: “Capable”,
“snpa”: “PtoP”,
“state”: “Up”,
“type”: “L1”
}
}
},
“HundredGigE0/1/0/23/0”: {
“neighbors”: {
“BU1”: {
“holdtime”: “20”,
“ietf_nsf”: “Capable”,
“snpa”: “PtoP”,
“state”: “Up”,
“type”: “L1”
}
}
}
},
“total_neighbor_count”: 7
}
}
}
}
},

My Code:

  • name: Print neighbors output
    debug:
    msg:
    - Key: “{{ items.key }}”
    - value: “{{ items.value }}”
    loop: “{{ parser_output | subelements() }}”

Trying to use subelements how doesnt seem to work.
Any help here ?

It might be worth formatting your example better, or maybe attaching a file or using pastebin.

Is this JSON? Have you tried playing with Selecting JSON data: JSON queries — Ansible Documentation ?

4 Likes

Hello @vicks, welcome to the Community!

Just wanted to complete @jrglynn2 answer (which is totally ok btw). If for any case you cannot install the jmespath library in order to use the json_query filter (e.g. you’re using an Ansible EE on a production environment not managed by you), you can also use the selectattr Jinja2 filter, which comes pretty handy on such cases. Refer to the docs for further examples:

https://docs.ansible.com/ansible/latest/playbook_guide/complex_data_manipulation.html

3 Likes