You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ansible 2.5.0中如何从字典列表获取指定node_port值

在Ansible中从字典列表提取指定条目的值

嗨,我来帮你搞定这个问题!你已经会用Python的lambda或生成器处理这种字典列表取值,在Ansible里其实也有很方便的实现方式,主要有两种常用方法,我给你详细拆解:

方法一:使用json_query过滤器(简洁高效)

json_query基于JMESPath语法,非常适合处理复杂的JSON结构查询。你可以直接过滤出name为"queue-port"的条目,再提取对应的node_port值:

首先假设你的字典列表存在变量ports_list中(就像你给的示例那样),通过set_fact来获取目标值:

- name: 提取queue-port的node_port值
  set_fact:
    queue_node_port: "{{ ports_list | json_query('[?name==`queue-port`].node_port | [0]') }}"

语法说明:

  • [?name==queue-port]:过滤出所有name字段等于"queue-port"的条目(注意JMESPath语法要求用反引号包裹字符串)
  • .node_port:从过滤后的条目中提取node_port字段,此时得到的是一个列表(比如[32614])
  • |[0]:取列表的第一个元素,得到最终的单个值32614

方法二:使用selectattr+map过滤器(原生无依赖)

如果你不想依赖JMESPath(虽然Ansible默认已包含jmespath库),可以用Ansible原生的过滤器组合实现:

- name: 提取queue-port的node_port值
  set_fact:
    queue_node_port: "{{ ports_list | selectattr('name', 'equalto', 'queue-port') | map(attribute='node_port') | first }}"

语法说明:

  • selectattr('name', 'equalto', 'queue-port'):筛选出name字段等于"queue-port"的条目
  • map(attribute='node_port'):从筛选后的条目里提取node_port字段,得到一个生成器对象
  • first:取生成器的第一个元素,也就是我们要的32614

处理无匹配的情况(可选)

如果担心列表里可能没有name为"queue-port"的条目,可以加上default过滤器避免报错:

# json_query写法
queue_node_port: "{{ ports_list | json_query('[?name==`queue-port`].node_port | [0]') | default(None, true) }}"

# selectattr写法
queue_node_port: "{{ ports_list | selectattr('name', 'equalto', 'queue-port') | map(attribute='node_port') | first | default(None, true) }}"

这样如果没有匹配项,变量会被设为None,而不是抛出错误。

举个完整示例,把你的字典列表作为变量:

vars:
  ports_list:
    - { "name": "queue-port", "node_port": 32614, "port": 5672, "protocol": "TCP", "target_port": 5672 }
    - { "name": "cluster-port", "node_port": 31018, "port": 4369, "protocol": "TCP", "target_port": 4369 }
    - { "name": "dist-port", "node_port": 30732, "port": 25672, "protocol": "TCP", "target_port": 25672 }

用上面任意一种方法,最终queue_node_port的值都会是32614。

内容的提问来源于stack exchange,提问作者user2363318

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:08:27