Looping over dictionaries

Looping over a simple list is nice. However, we often have an entity with more than one attribute associated with it. If you think about the vlan example in the last section, each vlan would have several unique attributes to it, such as the vlan description, the gateway IP address, and possibly others. Oftentimes, we can use a dictionary to represent the entity to incorporate multiple attributes to it.

Let's expand on the vlan example in the last section for a dictionary example in chapter8_6.yml. We defined the dictionary values for three vlans, each with a nested dictionary for the description and the IP address:

    <skip> 
vars:
cli:
host: "{{ ansible_host }}"
username: "{{ username }}"
password: "{{ password }}"
transport: cli
vlans: {
"100": {"description": "floor_1", "ip": "192.168.10.1"},
"200": {"description": "floor_2", "ip": "192.168.20.1"}
"300": {"description": "floor_3", "ip": "192.168.30.1"}
}

We can configure the first task, add vlans, by using the key of the each of items as the vlan number:

     tasks:
- name: add vlans
nxos_config:
lines:
- vlan {{ item.key }}
provider: "{{ cli }}"
with_dict: "{{ vlans }}"

We can proceed with configuring the vlan interfaces. Note that we use the parents parameter to uniquely identify the section the commands should be checked against. This is due to the fact that the description and the IP address are both configured under the interface vlan <number> subsection in the configuration:

  - name: configure vlans
nxos_config:
lines:
- description {{ item.value.name }}
- ip address {{ item.value.ip }}/24
provider: "{{ cli }}"
parents: interface vlan {{ item.key }}
with_dict: "{{ vlans }}"

Upon execution, you will see the dictionary being looped through:

TASK [configure vlans] *********************************************************
changed: [nxos-r1] => (item={'key': u'300', 'value': {u'ip': u'192.168.30.1', u'name': u'floor_3'}})
changed: [nxos-r1] => (item={'key': u'200', 'value': {u'ip': u'192.168.20.1', u'name': u'floor_2'}})
changed: [nxos-r1] => (item={'key': u'100', 'value': {u'ip': u'192.168.10.1', u'name': u'floor_1'}})

Let's check if the intended configuration is applied to the device:

nx-osv-1# sh run | i vlan
<skip>
vlan 1,10,100,200,300
nx-osv-1#
nx-osv-1# sh run | section "interface Vlan100"
interface Vlan100
description floor_1
ip address 192.168.10.1/24
nx-osv-1#
For more loop types of Ansible, feel free to check out the documentation (http://docs.ansible.com/ansible/playbooks_loops.html).

Looping over dictionaries takes some practice the first few times you use them. But just like standard loops, looping over dictionaries will be an invaluable tool in your tool belt.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset