使用 Ansible 从属性等于变量的 json 数组中检索值 [英] Retrieving value from json array where attribute equals variable with Ansible

查看:27
本文介绍了使用 Ansible 从属性等于变量的 json 数组中检索值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Ansible 获取 json 数组中的属性值.示例数据:

I'm trying to get the value of an attribute in a json array with Ansible. Example data:

"domains.json.data": [
        {
            "axfr_ips": [],
            "description": "",
            "domain": "mydomain.net",
            "expire_sec": 0,
            "group": "",
            "id": 687088,
        },
        {
            "axfr_ips": [],
            "description": "",
            "domain": "myotherdomain.net",
            "expire_sec": 0,
            "group": "",
            "id": 687089,
        }
    ]
}

所以我尝试使用 json 查询:

So I tried with json query:

"{{ domains.json.data | json_query(\"data[?domain=='{{ server_domain }}'].id\") }}"

或与:

- set_fact:
    domain_id: "{{ domains | json_query(query) | first }}"
  vars:
    query: "domains.json[?name=='{{ server_domain }}'].id"

也尝试过使用 selectattrib:

Also tried with selectattrib:

"{{ linode_domains.json.data | selectattr(\"domain\", \"{{ server_domain }}\") | list }}"

所以我需要的是获取我在 {{ server_domain }} 中获得的域的 id.

So what I need is to get the id of the domain I got in {{ server_domain }}.

推荐答案

查询无法工作,因为字典中没有name属性

The query can't work because there is no attribute name in the dictionary

        query: "domains.json[?name=='{{ server_domain }}'].id"

使用属性domain.例如下面的任务

Use the attribute domain. For example the task below

    - debug:
        msg: "{{ domains.json.data|json_query(query) }}"
      vars:
        server_domain: 'mydomain.net'
        query: "[?domain=='{{ server_domain }}'].id"

给予

    "msg": [
        687088
    ]

<小时>

注意事项


Notes

  • json_query 返回一个列表.
  • 使用过滤器 first 获取列表的第一个元素
  • json_query returns a list.
  • use filter first to get the first element of a list
        msg: "{{ domains.json.data|json_query(query)|first }}"

这篇关于使用 Ansible 从属性等于变量的 json 数组中检索值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆