首页 > 解决方案 > 如何在ansible中从字典中提取深度嵌套的数据

问题描述

我正在尝试从 ansible 字典中打印嵌套数据。但是,我无法弄清楚如何提取嵌套值。具体来说,在下面的数据中,我试图打印在“ipv4”下返回的两个值。目前,item.value.ipv4 的输出是下面括号中的部分:

"msg": "GigabitEthernet0/0/0,[{'address': '192.168.3.1', 'subnet': '28'}]"  

我想只使用这样的值:

"msg": "GigabitEthernet0/0/0, 192.168.3.1, 28"

我无法弄清楚如何将这些嵌套数据拉出来来做到这一点。简而言之,如果这样的事情可行,那就太好了:item.value.ipv4['address']。这是怎么做到的?

  tasks:

    - name: get config for Cisco IOS
      ios_facts:
        gather_subset: all
        gather_network_resources: interfaces

   - name: create dictionary with ansible_net_interfaces
      set_fact:
        foo_value: "{{ query('dict', ansible_net_interfaces) }}"

    - name: display the results of foo_value
      debug:
        msg: "{{ foo_value }}"

    - name: display certain detalys values from foo_value
      debug:
        msg: "{{ item.key }},{{ item.value.ipv4 }}"
      with_items: "{{ foo_value }}" 

这些任务产生以下结果:

TASK [display the results of foo] **********************************************************************************************************************
ok: [192.168.3.1] => {
    "msg": [
        {
            "key": "GigabitEthernet0/0/0",
            "value": {
                "bandwidth": 1000000,
                "description": "This is an interface description",
                "duplex": "Full",
                "ipv4": [
                    {
                        "address": "192.168.3.1",
                        "subnet": "28"
                    }
                ],
                "lineprotocol": "up",
                "macaddress": "50f7.123c.b0c0",
                "mediatype": "RJ45",
                "mtu": 1500,
                "operstatus": "up",
                "type": "ISR4331-3x1GE"
            }
        },
        {
            "key": "GigabitEthernet0/0/1",
            "value": {
                "bandwidth": 1000000,
                "description": "This is another interface description",
                "duplex": "Full",
                "ipv4": [
                    {
                        "address": "192.168.3.33",
                        "subnet": "30"
                    }
                ],
                "lineprotocol": "up",
                "macaddress": "50f7.123c.b0c0",
                "mediatype": "RJ45",
                "mtu": 1500,
                "operstatus": "up",
                "type": "ISR4331-3x1GE"
            }
        },
    ]
}

标签: ansible

解决方案


ipv4是一个字典列表。假设您只需要第一本字典,

    - name: display certain detalys values from foo_value
      debug:
        msg: "{{ item.key }},{{ item.value.ipv4[0].address }},{{ item.value.ipv4[0].subnet }}"
      when: item.value.ipv4 is defined and item.value.ipv4[0].subnet is defined and item.value.ipv4[0].address is defined 
      with_items: "{{ foo_value }}"

推荐阅读