i am trying to set facts from a json array, since the key contains space i am unable to parse, can someone help me here, i want to set fact as "name": "IN-FG-04" when "vdom": "vdom-shop"
Please see my sample playbook entry
- name: Iterate JSON
set_fact:
app_item: "{{ item['scope member'] }}"
with_items: "{{ result.results }}"
register: app_result
please see the json input and this is an output of my previous task
{
"msg": {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"failed": false,
"msg": "Custom Query Success",
"results": [
{
"name": "FG-04-Policy",
"obj ver": 3,
"oid": 1196,
"package settings": {
"central-nat": "disable",
"fwpolicy-implicit-log": "disable",
"fwpolicy6-implicit-log": "disable",
"inspection-mode": "proxy"
},
"scope member": [
{
"name": "IN-FG-04",
"vdom": "vdom-shop"
}
],
"type": "pkg"
},
{
"name": "FG-04-DC",
"obj ver": 23,
"oid": 1216,
"package settings": {
"central-nat": "disable",
"fwpolicy-implicit-log": "disable",
"fwpolicy6-implicit-log": "disable",
"inspection-mode": "proxy"
},
"scope member": [
{
"name": "IN-FG-04",
"vdom": "vdom1-dc"
}
],
"type": "pkg"
}
]
}
}
Note: although this is quite a good exercice for practicing loops, you should definitely consider fixing the previous task giving the result or write your own filter.
First of all, you are using
register
on aset_fact
task. It is not an error in itself but is of very limited interest. This will register if you correctly assigned a value to a variable, not the values themselves. So you will never get the expected result with this.What you want to do is to append items to a list while you are looping over your json in the
set_fact
task. This is done by initializing yourset_fact
variable to an empty list with thedefault
filter on first loop and appending a new list with your items.Moreover, since you need to look at several level of your object at the same time to take decisions, you need to use a
subelements
loop: loop level 0 on each result and level 1 on each element of thescope member
list. On each iteration, you will append an object to the list. In the example below, I used theternary
filter to decide which name to include.Which results in
The snippet below
gives: