如何在 Ansible 中有效访问嵌套的 JSON 对象

问题描述 投票:0回答:1

我有一个下面提到的 JSON 结构,但我不知道如何遍历层次结构中的较低部分:

"json": {
    "count": 5,
    "next": null,
    "previous": null,
    "results": [
        {
            "action": "pass",
            "application_groups": [],
            "applications": [],
           "created": "2024-06-20T09:53:20.139779+02:00",
            "custom_fields": {},
            "description": "",
            "destination_address_groups": [],
            "destination_addresses": [],
            "destination_service_groups": [],
            "destination_services": [
                {
                    "created": "2024-06-18T02:00:00+02:00",
                    "custom_fields": {},
                    "description": "",
                    "display": "ICMP (ICMP)",
                    "id": "c52f9be9-b4ca-4dd4-8993-2615c2fe004f",
                    "ip_protocol": "ICMP",
                    "last_updated": "2024-06-18T10:52:44.698368+02:00",
                    "name": "ICMP",
                    "natural_slug": "icmp__icmp_c52f",

我设法达到“二级”,但不比上面示例中的目标服务“更低”。不确定这是正确的方法,有人可以建议更好的/工作方法吗? 下面提到/尝试的点方法不起作用。我想这与列表、数组和字典的混合有关?

- name: API CALL (Nautobot GET rules)
  ansible.builtin.uri:
    url: https://{{ nautobot_ip }}/api/plugins/firewall/policy-rule/?depth=4
    method: GET
    validate_certs: false
    headers:
      Authorization: Token {{ nautobot_token }}
  register: firewall_rules

- name: SET FACT (Firewall policy rules)
  ansible.builtin.set_fact:
    firewall_policy_rules: "{{ firewall_rules['json']['results'] | json_query('[].{ dst_services: destination_services, dst_services_names: destination_services.names } ') }}"

我的目标是创建可用于进一步任务的所有防火墙规则的完整映射(字典)。我希望我的问题有意义。我还有一些对象的子对象比上面提到的目标服务还要多。

ansible ansible-facts
1个回答
0
投票

鉴于用于测试的简化mre数据

    firewall_rules:
      json:
        count: 2
        results:
        - action: pass
          created: '2024-06-20T09:53:20'
          destination_services:
          - {created: '2024-06-18T02:00:00', id: A}
          - {created: '2024-06-18T02:00:00', id: B}
        - action: deny
          created: '2024-06-20T09:53:20'
          destination_services:
          - {created: '2024-06-18T02:00:00', id: C}
          - {created: '2024-06-18T02:00:00', id: D}

以下查询

  fpr_query: '[].{key: action, value: destination_services}'
  fpr: "{{ firewall_rules.json.results | json_query(fpr_query) }}"

给予

  fpr:
    - key: pass
      value:
      - {created: '2024-06-18T02:00:00', id: A}
      - {created: '2024-06-18T02:00:00', id: B}
    - key: deny
      value:
      - {created: '2024-06-18T02:00:00', id: C}
      - {created: '2024-06-18T02:00:00', id: D}

您可以将其转换为字典

 fpr | items2dict:
    deny:
    - {created: '2024-06-18T02:00:00', id: C}
    - {created: '2024-06-18T02:00:00', id: D}
    pass:
    - {created: '2024-06-18T02:00:00', id: A}
    - {created: '2024-06-18T02:00:00', id: B}
© www.soinside.com 2019 - 2024. All rights reserved.