Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible - How to combine two separate lists into a list of dictionaries

Tags:

ansible

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?

like image 828
Litame Avatar asked Aug 17 '18 15:08

Litame


People also ask

How to merge two dicts in Ansible?

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.

How do I merge two dictionaries in a single expression?

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.


1 Answers

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 }}"
like image 194
techraf Avatar answered Oct 10 '22 09:10

techraf