如何使用嵌套字典循环字典

时间:2021-05-18 20:57:47

标签: ansible

从下面的 json 中,我需要在循环中收集接口名称和单元名称值。 这是我的 json 的部分输出:

{
    "configuration": {
        "@": {
            "junos:changed-localtime": "2021-04-30 12:47:05 PDT",
            "junos:changed-seconds": "1619812025",
            "xmlns": "http://xml.juniper.net/xnm/1.1/xnm"
        },
        "interfaces": {
            "interface": [
                {
                    "name": "irb",
                    "unit": [
                        {
                            "family": {
                                "inet": {
                                    "address": [
                                        {
                                            "name": "100.111.10.4/24"
                                        }
                                    ],
                                    "mtu": 9100
                                }
                            },
                            "name": 4010
                        },
                        {
                            "family": {
                                "inet": {
                                    "address": [
                                        {
                                            "name": "100.127.9.2/31"
                                        }
                                    ]
                                }
                            },
                            "name": 4093
                        }
                    ]
                },
                {
                    "name": "lo0",
                    "unit": [
                        {
                            "family": {
                                "inet": {
                                    "address": [
                                        {
                                            "name": "100.127.0.32/32"
                                        }
                                    ],
                                    
                                }
                            },
                            "name": 0
                        }
                    ]
                }
            ]
        }
    }
}

我使用的剧本如下:

- name: Print response
  debug:
    msg: "{{item.name}}.{{item|json_query('unit[*].name')}}"
  loop: "{{ test.parsed_output.configuration.interfaces.interface}}"
  ignore_errors: yes

我遇到的问题是:

"msg": "lo0.[0]"
"msg": "irb.[4010, 4093]"

我想得到的是:

"msg": "lo0.0"
"msg": "irb.4010"
"msg": "irb.4093"

与每个 unit.name 的外部名称相同,但我不知道该怎么做。

谢谢。

1 个答案:

答案 0 :(得分:0)

迭代with_subelements,例如

    - debug:
        msg: "{{ item.0.name }} {{ item.1.name }}"
      with_subelements:
        - "{{ test.parsed_output.configuration.interfaces.interface }}"
        - unit

给予

  msg: irb 4010
  msg: irb 4093
  msg: lo0 0