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 Articles • Ansible Variables: Complete Guide • Ansible Jinja2 Filters Reference • Ansible Playbook Guide
Category: database-automation