我有两个单独的清单。第一个是Ansible收集的网络接口列表:
"ansible_interfaces": [
"ens32",
"ens34"
],
Run Code Online (Sandbox Code Playgroud)
第二个是我在清单中手动定义的IP地址列表:
host_ipv4_list:
- "192.168.0.1"
- "192.168.1.1"
Run Code Online (Sandbox Code Playgroud)
我的目的是将这两个列表结合起来,以获得带有键和值的字典,如下所示:
host_network_info:
- { "interface": "ens32", "ip": "192.168.0.1" }
- { "interface": "ens34", "ip": "192.168.1.1" }
Run Code Online (Sandbox Code Playgroud)
最好的方法是什么?
压缩两个列表,并使用生成的列表元素创建字典。将字典组合成一个循环:
set_fact:
host_network_info: "{{ host_network_info | default([]) + [dict(interface=item[0], ip=item[1])] }}"
loop: "{{ ansible_interfaces | zip(host_ipv4_list) | list }}"
Run Code Online (Sandbox Code Playgroud)
小智 5
无循环解决方案:
- set_fact:
host_network_info: "{{ dict(ansible_interfaces | zip(host_ipv4_list)) |
dict2items(key_name='interface', value_name='ip') }}"
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3009 次 |
最近记录: |