Reputation: 33
I would like to combine two lists into a key, value dictionary in Ansible.
I have the following lists (AWS resource IDs):
ok: [localhost] => {
"vpc_natgw_ids": [
[
"vpc-123",
"vpc-234",
"vpc-345",
"vpc-456"
],
[
"nat-098",
"nat-987",
"nat-876",
"nat-765"
]
]
}
The first item in the first list corresponds to the first item in the second list, the second item to the other second item and so on.
I'd like to combine the two lists to get a dict like so:
ok: [localhost] => {
"vpc_natgw_ids_dict": [
"vpc-123": "nat-098",
"vpc-234": "nat-987",
"vpc-345": "nat-876",
"vpc-456": "nat-765"
]
}
How would I achieve something like this?
Upvotes: 3
Views: 3950
Reputation: 33
Another solution posted by IRC user seschwar in #ansible on freenode.net works as well by utilizing Jinja2:
- set_fact:
vpc_natgw_ids_dict: >-
{%- set ns = namespace(ids={}) -%}
{%- for i in vpc_natgw_ids[0] -%}
{{- ns.ids.__setitem__(vpc_natgw_ids[0][loop.index0], vpc_natgw_ids[1][loop.index0]) -}}
{%- endfor -%}
{{- ns.ids -}}
- debug:
var: vpc_natgw_ids_dict
Upvotes: 0
Reputation: 68469
For example this way:
set_fact:
vpc_natgw_ids_dict: "{{ dict(vpc_natgw_ids[0] | zip(vpc_natgw_ids[1])) }}"
Upvotes: 4