Given my_dict the play
vars:
my_dict:
key1: { "key1a": ["key1aa": "value1aa", "key1ab": "value1ab"]}
key2: { "key2a": ["key2aa": "value2aa", "key2ab": "value2ab"]}
tasks:
- set_fact:
my_list: "{{ my_list|default([]) + [{item.key: item.value}] }}"
loop: "{{ my_dict|dict2items }}"
- debug:
msg: "{{ my_list|to_json }}"
gives
msg: '[{"key2": {"key2a": [{"key2aa": "value2aa"}, {"key2ab": "value2ab"}]}},
{"key1": {"key1a": [{"key1aa": "value1aa"}, {"key1ab": "value1ab"}]}}]'
The output was printed with yaml
callback (export ANSIBLE_STDOUT_CALLBACK=yaml
). Then the output was split manually after the first item of the list.
json_query
It is also possible to create the list with jmespath
i.e. json_query
. For example, the task below gives the same result
- set_fact:
my_list: "{{ my_dict|
dict2items|
json_query('[].[{key: key, value: value}]')|
map('items2dict')|
list }}"
to_nice_yaml
It's easier to see the data's structure when printed with the filter to_nice_yaml
. For example
- debug:
msg: "{{ my_list|to_nice_yaml }}"
gives
msg: |-
- key2:
key2a:
- key2aa: value2aa
- key2ab: value2ab
- key1:
key1a:
- key1aa: value1aa
- key1ab: value1ab
filter_plugins
It's also possible to use custom Filter plugins. For example with the plugin
$ cat filter_plugins/dict_utils.py
def dict2list(d):
l = []
for i in d:
h = {i:d[i]}
l.append(h)
return l
class FilterModule(object):
def filters(self):
return {
'dict2list': dict2list
}
the task below gives the same result
- set_fact:
my_list: "{{ my_dict|dict2list }}"
For your convenience: