Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible: Convert two lists into key, value dict

Tags:

ansible

I have 2 lists as set_fact and want to create a dict

I am running ansible 2.8 I have list1 as below

  "inventory_devices": [
        "device0", 
        "device1" 
    ]

and list2 as below

"inventory_ips": [
    "10.1.1.1", 
    "10.1.1.2" 
]

I want to get an output shows like

"inventory_dict": [
    "device0": "10.1.1.1",
    "device1": "10.1.1.2"
]

Thanks.

like image 878
user3305223 Avatar asked Oct 19 '25 17:10

user3305223


1 Answers

You can do it entirely with jinja2 using the zip filter built into ansible.

To get a list combining the elements of other lists use zip

- name: give me list combo of two lists
  debug:
    msg: "{{ [1,2,3,4,5] | zip(['a','b','c','d','e','f']) | list }}"

...

Similarly to the output of the items2dict filter mentioned above, these filters can be used to contruct a dict:

{{ dict(keys_list | zip(values_list)) }}

The zip filter sequentially combines items from pairs of lists and the dict construct creates a dictionary from a list of pairs.

inventory_dict: "{{ dict(inventory_devices | zip(inventory_ips)) }}"
like image 166
Calum Halpin Avatar answered Oct 22 '25 00:10

Calum Halpin