How to Loop Over Dictionaries in Ansible

How to Loop Over Dictionaries in Ansible

Ansible Tip:

Use the dict2items filter to loop over dictionaries in Ansible.

Here's an example:

---
- name: Example of dict2items filter
  hosts: localhost
  gather_facts: false

  vars:
    interfaces:
      eth0:
        ip: "192.168.1.1/24"
      eth1:
        ip: "192.168.2.1/24"

  tasks:
    - ansible.builtin.debug:
        msg: |
          Interface: {{ item.key }}
          IP Address: {{ item.value.ip }}
      loop: "{{ interfaces | dict2items }}"
# Output:
# ok: [localhost] => (item={'key': 'eth0', 'value': {'ip': '192.168.1.1/24'}}) => 
#   msg: |-
#     Interface: eth0
#     IP Address: 192.168.1.1/24
# ok: [localhost] => (item={'key': 'eth1', 'value': {'ip': '192.168.2.1/24'}}) => 
#   msg: |-
#     Interface: eth1
#     IP Address: 192.168.2.1/24

Subscribe to our newsletter and stay updated.

Don't miss anything. Get all the latest posts delivered straight to your inbox.
Great! Check your inbox and click the link to confirm your subscription.
Error! Please enter a valid email address!