Looping over dictionaries

Looping over a simple list is nice. However, we often have an entity with more than one attributes associate with it. If you think of the vlan example in the last section, each vlan would have several unique attributes to it, such as vlan description, the IP address, and possibly others. Often times, 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 chapter5_6.yml. We defined the dictionary values for three vlans, each has a nested dictionary for 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, using the key of the each of the item 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 interface. Notice 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:

  - 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 us 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 when 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
18.216.44.143