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

Ansible如何基于IVR名称过滤JSON中的对应ID值?

根据IVR名称获取对应ID值

现有查询返回结果

ok: [oc-ar-ar-test-ansible-api] => {
    "ivr_list.json": [
        {
            "announcement": {
                "id": "0",
                "name": "None"
            },
            "dests": {
                "i": {
                    "id": "101",
                    "name": "Pablo Gonzalez",
                    "type": "Extension"
                },
                "t": {
                    "id": "100",
                    "name": "Fruta Peralta",
                    "type": "Extension"
                }
            },
            "id": "3",
            "loops": "2",
            "name": "Prueba",
            "timeout": "10"
        },
        {
            "announcement": {
                "id": "8",
                "name": "General-ES"
            },
            "dests": {
                "i": {
                    "id": "10000",
                    "name": "General",
                    "type": "Queue"
                },
                "t": {
                    "id": "10000",
                    "name": "General",
                    "type": "Queue"
                }
            },
            "id": "23",
            "loops": "2",
            "name": "General-ES",
            "timeout": "10"
        }
    ]
}

需求

根据指定IVR名称(例如General-ES),获取对应的id值(例如23)。此前尝试的方案要么返回固定ID,要么无结果,需要修正。

解决方案

利用Ansible的json_query过滤器可以精准实现这个需求,以下是具体实现步骤:

1. 核心过滤表达式

针对你的数据结构,使用json_query筛选匹配指定名称的IVR并提取ID:

{{ ivr_list.json | json_query('[?name==`' ~ target_ivr_name ~ '`].id | [0]') }}
  • [?name==' ~ target_ivr_name ~ ']:筛选出name字段等于目标名称的IVR对象
  • .id:提取筛选结果中的id字段
  • | [0]:取第一个匹配结果(假设IVR名称唯一,若需返回所有匹配结果可去掉此部分)

2. 完整Ansible任务示例

- name: 获取指定IVR的ID
  set_fact:
    target_ivr_id: "{{ ivr_list.json | json_query('[?name==`' ~ target_ivr_name ~ '`].id | [0]') }}"
  vars:
    target_ivr_name: "General-ES"  # 替换为你需要查询的IVR名称

3. 常见问题排查

  • 大小写与空格匹配:确保target_ivr_name的值与数据中name字段完全一致,包括大小写、空格和特殊字符
  • 多同名IVR处理:如果存在多个同名IVR,去掉| [0]会返回所有匹配的ID数组
  • 引号语法:json_query中字符串必须用反引号`包裹,因此拼接变量时要注意Ansible的字符串拼接规则

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 17:52:39