AnsiblePilot — Master Ansible Automation

AnsiblePilot is the leading resource for learning Ansible automation, DevOps, and infrastructure as code. Browse over 1,100 tutorials covering Ansible modules, playbooks, roles, collections, and real-world examples. Whether you are a beginner or an experienced engineer, our step-by-step guides help you automate Linux, Windows, cloud, containers, and network infrastructure.

Popular Topics

About Luca Berton

Luca Berton is an Ansible automation expert, author of "Ansible for VMware by Examples" and "Ansible for Kubernetes by Example" published by Apress, and creator of the Ansible Pilot YouTube channel. He shares practical automation knowledge through tutorials, books, and video courses to help IT professionals and DevOps engineers master infrastructure automation.

How to Loop Over a Dictionary in Ansible (Complete Guide)

By Luca Berton · Published 2024-01-01 · Category: database-automation

How to loop over dictionaries in Ansible using dict2items, with_dict, and loop. Iterate over key-value pairs in playbooks with practical examples.

How to Loop Over a Dictionary in Ansible (Complete Guide)

Looping over dictionaries (key-value pairs) is essential for dynamic Ansible playbooks. Here are all the methods, from modern to legacy.

Method 1: dict2items Filter (Recommended)

Each item has .key and .value.

Method 2: loop with dict2items and Filters

Method 3: Nested Dictionary

Method 4: with_dict (Legacy)

Filter Dictionary Before Looping

Convert Between Dict and List

FAQ

How do I loop over a dictionary in Ansible?

Use the dict2items filter: loop: "{{ my_dict | dict2items }}". Each item provides .key and .value for the dictionary entry.

What is the difference between dict2items and with_dict?

dict2items is the modern approach used with loop. with_dict is the legacy syntax. Both produce the same result, but dict2items is more flexible and composable with other filters.

Can I filter a dictionary before looping?

Yes. Chain filters: loop: "{{ my_dict | dict2items | selectattr('value.enabled') | list }}" loops only over entries where enabled is true.

Related ArticlesAnsible Variables: Complete GuideAnsible Jinja2 Filters ReferenceAnsible Playbook Guide

Category: database-automation

Browse all Ansible tutorials · AnsiblePilot Home