如何使用 JMESPATH 或 json_query 从 json 输出中过滤多个键值以在 ansible 中使用?

how to filter multiple keys value from json output using JMESPATH or json_query to use in ansible?

我想使用 json_query 从 json 下面过滤每个键值 | JMESPATH,如何实现?

{
  "facts_hash": {
    "processors::count": "96",
    "processors::physicalcount": "2",
    "processor0": "Intel(R) Xeon(R) Gold 6252 CPU @ 2.10GHz",
    "processorcount": "96",
    "macaddress": "08:f1:ea:6d:04:3G",
    "ipaddress": "192.168.101.135",
    "manufacturer": "HPE",
    "productname": "ProLiant DL360 Gen10",
    "serialnumber": "SGH93GDCR",
    "memorysize_mb": "773730.12",
    "ipmi_ipaddress": "172.16.200.28",
      },
  "id": 284
}

预期输出,可以如下所示

  [ "96",
    "2",
    "Intel(R) Xeon(R) Gold 6252 CPU @ 2.10GHz",
    "96",
    "08:f1:ea:6d:03:3c",
    "192.168.101.135",
    "HPE",
    "ProLiant DL360 Gen10",
    "SGH936XG91",
    "773730.12",
    "172.16.100.24",
    "284" ]

这是我试过的以下查询,其中 return 值。

"{{ facts_hash | json_query('[manufacturer, ipaddress, macaddress, productname, serialnumber, processorcount, processor0, memorysize_mb, ipmi_ipaddress]') | list }}"

在 json 中有几个键,有四个 :: 我无法在这里过滤的是那些键 "processors::count" 和 "processors::physicalcount" 以及我无法获取 "id"

查询return值。

 ok: [localhost] => {
    "ansible_facts": {
        "allvalue": [
            "HPE",
            "192.168.101.135",
            "08:f1:ea:6d:03:3c",
            "ProLiant DL360 Gen10",
            "SGH936XG91",
            "96",
            "Intel(R) Xeon(R) Gold 6252 CPU @ 2.10GHz",
            "773730.12",
            "172.16.100.24"
        ]
    },
    "changed": false
}

谢谢

我会用 facts_hash | dict2items | map(attribute="value") | list 自己来做,但是你的问题的答案似乎是在 JMESPath 选择器中引用键名:

- debug:
    msg: "{{ facts_hash |
      json_query('[\"processors::count\",  \"processors::physicalcount\", manufacturer, ipaddress, macaddress, productname, serialnumber, processorcount, processor0, memorysize_mb, ipmi_ipaddress]') | list }}"

哪一个可以通过将 JMESPath 表达式提取到它自己的局部变量来使其更易读:

- debug:
    msg: "{{ facts_hash | json_query(facts_query) | list }}"
  vars:
    facts_query: '["processors::count", "processors::physicalcount", manufacturer, ipaddress, macaddress, productname, serialnumber, processorcount, processor0, memorysize_mb, ipmi_ipaddress]'

至于

along with i am not able to fetch the "id"

那是因为 idfacts_hash 兄弟 ,所以无论结构包含 facts_hash,您正在做的是 set_fact: 来提取 facts_hash,您需要类似的提取来获取其 id 字段