How do I convert a dictionary like below
{
"host1": ["tag1", "tag2"],
"host2": ["tag1"]
}
to below in ansible:
{
"tag1": ["host1","host2"],
"tag2": ["host1"]
}
I have been trying to do this but got stuck due to the value being a list.
The playbook
shell> cat playbook.yml
- hosts: localhost
vars:
dict1:
host1: ["tag1", "tag2"]
host2: ["tag1"]
tasks:
- set_fact:
dict2: "{{ dict2|default({})|
combine({item: list_of_hosts}) }}"
loop: "{{ dict1.values()|flatten|unique|list }}"
vars:
list_of_hosts: "{{ dict1|
dict2items|
selectattr('value', 'contains', item)|
map(attribute='key')|
list }}"
- debug:
var: dict2
gives
"dict2": {
"tag1": [
"host1",
"host2"
],
"tag2": [
"host1"
]
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.