Loop Over Dictionary Attribute in Ansible
Working with variables can sometimes get tricky in Ansible. Say, you have a dictionary where you want loop over a certain attribute, not all values. For example, when your variables are declared like this:
interfaces: eth0: ip: 10.0.0.10 mask: 16 eth1: ip: 192.168.1.100 mask: 24
How do you just loop over all the IP addresses? This is where the map filter comes in:
vars: ip_addresses: "{{ interfaces.values() | map(attribute='container') | list }}"
The snippet takes all values from the interfaces
dictionary (eth0
, eth1
) and then extracts the ip
attribute from them. Finally, it casts the result into list.
Ansible filters are a very powerful tool, so I would recommend you take some time to read it thoroughly. If you are looking for more Ansible tips, such as how to make a playbook distribution agnostic or setup your laptop with Ansible, look here.