问题原文
原帖链接 · kuda · CC BY-SA 4.0
I have two lists:
"combo_all": [
[
null,
"3",
"210
],
[
"r0004",
"65",
"212"
]
and
"zone_name_list": [
{
"dns_zone_id": 10423,
"name": "212.18.172.in-addr.arpa."
},
{
"dns_zone_id": 10424,
"name": ""210.18.172.in-addr.arpa."."
}
How can I replace the third item in the "combo_all" (first list) by the "dns_zone_id" number (from the second list) whenever the first octet from the "name" matches the third item from the first list (210, 212)?
已采纳解答
原帖链接 · Vladimir Botka · CC BY-SA 4.0
Create the dictionary octet1_id
dns_zone_id: "{{ zone_name_list|map(attribute='dns_zone_id') }}"
octet1: "{{ zone_name_list|map(attribute='name')
|map('split', '.')
|map('first') }}"
octet1_id: "{{ dict(octet1|zip(dns_zone_id)) }}"
gives
octet1_id:
'210': 10424
'212': 10423
Then create a list
- set_fact:
combo_id: "{{ combo_id|d([]) + [item[:-1] + [octet1_id[item[-1]]]] }}"
loop: "{{ combo_all }}"
gives
combo_id:
- [null, '3', 10424]
- [r0004, '65', 10423]
Example of a complete playbook for testing
- hosts: all
vars:
combo_all:
- [ null, "3", "210"]
- [ "r0004", "65", "212"]
zone_name_list:
- {dns_zone_id: 10423, name: 212.18.172.in-addr.arpa.}
- {dns_zone_id: 10424, name: 210.18.172.in-addr.arpa.}
dns_zone_id: "{{ zone_name_list|map(attribute='dns_zone_id') }}"
octet1: "{{ zone_name_list|map(attribute='name')
|map('split', '.')
|map('first') }}"
octet1_id: "{{ dict(octet1|zip(dns_zone_id)) }}"
tasks:
- debug:
var: dns_zone_id
- debug:
var: octet1
- debug:
var: octet1_id
- set_fact:
combo_id: "{{ combo_id|d([]) + [item[:-1] + [octet1_id[item[-1]]]] }}"
loop: "{{ combo_all }}"
- debug:
var: combo_id|to_yaml
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
