我似乎无法在Ansible中解决这个问题,但可以在Python中轻松完成。 我有两个不同的列表从模块返回给我。模块(ntc-ansible)实际上是连接到网络交换机并使用两个不同的show命令获取端口信息。基本上我想迭代列表#1和列表#2,如果端口#匹配,则将每个列表中的变量合并到一个新列表中。例如,我可能会从模块中获取此信息(以及更多数据):
list1 = [
{
"description": "Switch #1",
"port": "Gi1/1",
"protocol": "up",
"status": "up"
},
{
"description": "Switch #2",
"port": "Gi1/5",
"protocol": "up",
"status": "up"
}
]
list2 = [ {
{
"duplex": "a-full",
"name": "Switch #1",
"port": "Gi1/1",
"speed": "a-1000",
"status": "connected",
"type": "10/100/1000BaseT",
"vlan": "trunk"
},
{
"duplex": "a-full",
"name": "Some Server",
"port": "Gi1/2",
"speed": "a-100",
"status": "connected",
"type": "10/100/1000BaseT",
"vlan": "trunk"
}
]
我想循环遍历list1然后循环遍历list2。如果端口匹配,则将dict条目合并到一个新列表中,以便为相关端口获取正确的变量。更糟糕的是,我不想合并所有变量,只选择一些变量。
希望我有意义......如果我在Python中这样做,我可能会这样做:
new_list = []
for port_a in list1:
temp_dict = {}
for port_b in list2:
if port_a['port'] == port_b['port']:
temp_dict['port'] = port_a['port']
temp_dict['desc'] = port_a['description']
temp_dict['status'] = port_b['status']
temp_dict['vlan'] = port_b['vlan']
temp_dict['speed'] = port_b['speed']
temp_dict['duplex'] = port_b['duplex']
temp_dict['type'] = port_b['type']
new_list.append(temp_dict)
在上面的列表中,我只会获得端口" Gi1 / 1"在新名单中。
答案 0 :(得分:0)
您可以使用with_together
。
- set_fact:
new_list: "{{ new_list|default([]) + [' {{item.0}}|union({{item.1}}) '] }}"
when: item.0.port == item.1.port
with_together:
- "{{list1}}"
- "{{list2}}"