I have two separate lists. The first one is a list of network interfaces gathered by Ansible:
"ansible_interfaces": [
"ens32",
"ens34"
],
The second one is a list of IP addresses that I define manually in the inventory:
host_ipv4_list:
- "192.168.0.1"
- "192.168.1.1"
My aim is to combine those two lists in order to get a dictionary with keys and values, that look like this:
host_network_info:
- { "interface": "ens32", "ip": "192.168.0.1" }
- { "interface": "ens34", "ip": "192.168.1.1" }
What would be the best way to do this?
If you have two or more lists of dictionaries and want to combine them into a list of merged dictionaries, where the dictionaries are merged by an attribute, you can use the lists_mergeby filter. The output of the examples in this section use the YAML callback plugin.
Using | in Python 3.9 In the latest update of python now we can use “|” operator to merge two dictionaries. It is a very convenient method to merge dictionaries.
Zip the two lists and use the resulting list elements to create dictionaries. Combine the dictionaries in a loop:
set_fact:
host_network_info: "{{ host_network_info | default([]) + [dict(interface=item[0], ip=item[1])] }}"
loop: "{{ ansible_interfaces | zip(host_ipv4_list) | list }}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With