如何从嵌套JSON数组中筛选DHCP类型的网络接口名称?
筛选DHCP类型的接口名称(Ansible)
需求说明
给定如下JSON结构的网络配置数据:
{ "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" } ] } ] } ] }
需要筛选出所有包含type: DHCP条目的接口名称,预期输出为:
['ens5f0', 'ens5f2']
问题重现
尝试了以下Ansible任务,但返回结果是nets中的DHCP条目(而非接口名称):
- 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" }
解决方案
方法一:使用Ansible过滤器链
核心思路是先筛选出符合条件的接口对象,再提取接口名称:
- name: 获取DHCP接口名称 set_fact: dhcp_interfaces: "{{ main_host_network_interfaces[0].interfaces | selectattr('nets', 'any', {'type': 'DHCP'}) | map(attribute='name') | list }}"
各过滤器作用:
selectattr('nets', 'any', {'type': 'DHCP'}):筛选出nets列表中存在type: DHCP条目的接口对象map(attribute='name'):提取这些接口对象的name属性list:将结果转换为列表
方法二:使用json_query(更简洁)
利用JMESPath语法直接查询:
- name: 获取DHCP接口名称(json_query方式) set_fact: dhcp_interfaces: "{{ main_host_network_interfaces | json_query('host[0].interfaces[?nets[*].type==`DHCP`].name') }}"
JMESPath表达式说明:
host[0].interfaces:定位到接口列表[?nets[*].type==DHCP]:筛选出nets中存在DHCP类型的接口.name:提取这些接口的名称字段
最终结果
运行上述任一任务后,dhcp_interfaces变量的值将为:
['ens5f0', 'ensf2']
内容的提问来源于stack exchange,提问作者Venkatesh Parthasarathy
相关产品推荐
相关产品推荐

