嵌套字典上的Ansible循环

时间:2018-11-20 23:05:30

标签: ansible

我从API调用中返回了以下数据

"napalm_interfaces_ip": {
    "Vlan5": {
        "ipv4": {
            "10.45.230.250": {
                 "prefix_length": 24
            }
        }
     }
 }

如何调试打印VLAN信息,IP和前缀长度?

这就是我所拥有的

- debug:
     msg: "Interface: {{ item.key }}, IP: {{ item.value.ipv4 }}"
  with_dict:
     - "{{ napalm_interfaces_ip }}"

它会产生以下输出,显示指向另一个字典的IP

  

任务[validate_device_ips:调试]

     
     

ok:[] =>(项目= {'value':{u'ipv4':{u'10.45.230.250':   {u'prefix_length':24}}},'key':u'Vlan5'})=> {      “ msg”:“接口:Vlan5,IP:{u'10.45.230.250':{​​u'prefix_length':24}}”“}

1 个答案:

答案 0 :(得分:0)

dict2items应该会帮助:

- debug:
    msg: "IP: {{ item.key }} prefix_length: {{ item.value.prefix_length }}"
  loop: "{{ napalm_interfaces_ip.Vlan5.ipv4 | dict2items }}"

with_dict 也可以

- debug:
    msg: "IP: {{ item.key }} prefix_length: {{ item.value.prefix_length }}"
  with_dict: "{{ napalm_interfaces_ip.Vlan5.ipv4 }}"

下面是如何循环接口的示例

- hosts: localhost
  gather_facts: no
  vars:
    interfaces:
      - Vlan0:
          ipv4:
            10.45.230.250:
              prefix_length: 24
      - Vlan1:
          ipv4:
            10.45.230.251:
              prefix_length: 24
      - Vlan2:
          ipv4:
            10.45.230.252:
              prefix_length: 24
  tasks:
    - name: List selected variables
      vars:
        msg: |
          vlan {{ item|dict2items|json_query('[].key') }}
          ip {{ item|dict2items|json_query('[].value.ipv4|[0]')|dict2items|json_query('[].key') }}
          prefix {{ item|dict2items|json_query('[].value.ipv4|[0]')|dict2items|json_query('[].value.prefix_length') }}
      debug:
        msg: "{{ msg.split('\n') }}"
      loop: "{{ interfaces }}"

一旦您决定让生活更轻松,请选择以下选项

- hosts: localhost
  vars:
    interfaces:
      - Vlan0:
          ipv4: "10.45.230.250"
          prefix_length: "24"
      - Vlan1:
          ipv4: "10.45.230.251"
          prefix_length: "24"
      - Vlan2:
          ipv4: "10.45.230.252"
          prefix_length: "24"
  tasks:
    - name: List selected variables
      vars:
        msg: |
          vlan {{ item|dict2items|json_query('[].key') }}
          ip {{ item|dict2items|json_query('[].value.ipv4') }}
          prefix {{ item|dict2items|json_query('[].value.prefix_length') }}
      debug:
        msg: "{{ msg.split('\n') }}"
      loop: "{{ interfaces }}"