I use Ansible to get some info from a firewall which returns the output as JSON. If the firewall has more than one package installed, it will return a list of dictionaries. If there is only a single package, it returns a dictionary. Let's say there is only one package installed so, it returns a dictionary - How do I add this dictionary as an item to a new list? So, the new list will only have a single element in it.
In a nutshell, how do I add a dictionary as an item to a new list?
The dictionary can be accessed here when a single package is installed.
(output.stdout | from_json).result.system.packages.entry
multiple packages
"packages": {
"entry": [
{
"name": "package-1",
"version": "1.1.0",
"info": "installed"
},
{
"name": "package-2",
"version": "1.0.0",
"info": "installed"
}
]
}
single package
"packages": {
"entry": {
"name": "package-1",
"version": "1.1.0",
"info": "installed"
}
}
EDIT
- name: "Set fact"
set_fact:
result: "{{ (output.stdout | from_json).result.system.packages.entry }}"
- name: "debug"
debug:
msg:
- "{{ result | type_debug }}"
- "{{ result }}"
!! RESULT !!
"msg": [
"dict",
{
"name": "package-1",
"version": "1.1.0",
"installed": "yes"
}
]
- name: "Set fact"
set_fact:
result: []
- name: append dict to list
set_fact:
result = "{{ [(output.stdout | from_json).result.system.packages.entry] }}"
- name: "debug"
debug:
msg:
- "{{ result | type_debug }}"
- "{{ result }}"
!! RESULT !!
"msg": [
"list",
[]
] ```