Merging two dictionaries by key in Ansible
I'm looking for help in merging two dictionaries in a specific way. I would be very grateful for any thoughts.
I have two dictionaries like this: 1st dict:
servers:
server1:
Property1: A
Property2: B
Property3: C
server2:
Property1: A
Property2: B
Property3: C
2nd dict:
management:
server1: ip1_addr
server2: ip2_addr
Desired result:
servers:
server1:
Property1: A
Property2: B
Property3: C
Property4: ip1_addr
server2:
Property1: A
Property2: B
Property3: C
Property4: ip2_addr
Or I may have chosen the wrong path, all I need is to loop over two that dictionaries in one go, to get ip1_addr under server1 key and ip2_addr under server2 key
Solution 1:
Convert the dictionary management first
- set_fact:
mgmt: "{{ mgmt|d({})|combine({item.key: {'Property4': item.value}}) }}"
loop: "{{ management|dict2items }}"
gives
mgmt:
server1:
Property4: ip1_addr
server2:
Property4: ip2_addr
Then combine the dictionaries
- set_fact:
servers: "{{ servers|combine(mgmt, recursive=True) }}"
gives the desired result
servers:
server1:
Property1: A
Property2: B
Property3: C
Property4: ip1_addr
server2:
Property1: A
Property2: B
Property3: C
Property4: ip2_addr
If you want to iterate the result it's easier to convert both dictionaries to lists
- set_fact:
mgmt: "{{ mgmt|d([]) + [{'server': item.key,
'Property4': item.value}] }}"
loop: "{{ management|dict2items }}"
- set_fact:
srvs: "{{ srvs|d([]) + [{'server': item.key}|combine(item.value)] }}"
loop: "{{ servers|dict2items }}"
give
mgmt:
- Property4: ip1_addr
server: server1
- Property4: ip2_addr
server: server2
srvs:
- Property1: A
Property2: B
Property3: C
server: server1
- Property1: A
Property2: B
Property3: C
server: server2
Then use Community.General filter lists_mergeby
- debug:
msg: "{{ srvs|lists_mergeby(mgmt, 'server') }}"
gives
msg:
- Property1: A
Property2: B
Property3: C
Property4: ip1_addr
server: server1
- Property1: A
Property2: B
Property3: C
Property4: ip2_addr
server: server2