我有以下 JSON 结构,如果类型为“DHCP”,我想获取接口名称。
{
"host": [
{
"interfaces": [
{
"bootproto": "none",
"name": "ens5f0",
"nets": [
{
"ipaddr": "10.1.1.10",
"type": "DHCP",
},
{
"ipaddr": "10.1.1.10",
"type": "STATIC",
}
]
},
{
"bootproto": "none",
"name": "ens5f1",
"nets": [
{
"ipaddr": "10.1.1.11",
"type": "STATIC",
}
]
},
{
"bootproto": "none",
"name": "ensf2",
"nets": [
{
"ipaddr": "192.168.1.1",
"type": "DHCP",
}
]
}
]
}
]
}
这里的预期输出是
['ens5f0', 'ens5f2']
我尝试在下面的 Ansible play 中获取安装名称。
- name: Get DHCP interface name
set_fact:
dhcp_interfaces: "{{ main_host_network_interfaces[0].interfaces | map(attribute='nets') | flatten | selectattr('type', 'match', 'DHCP') | list }}"
但它返回
{
"ipaddr": "10.1.1.10",
"type": "DHCP",
}
好吧!
试试这个:
set_fact:
interfaces: "{{ host[0].interfaces | selectattr('nets.type', 'equalto', 'DHCP') | map(attribute='name') | list }}"
equalto 是在 2.8 版本中添加的,您可以通过 pip list | 检查它是否可用。 grep Jinja2. equalto 在版本中引入。 2.8.