Ansible in a Minute · Ansible Core ·
Use dict2items to loop a dictionary
Short answer
Pipe a dictionary through dict2items so loop can walk each key and value.
Subscribe for updates
Get an email whenever we publish new guides and blog posts. Unsubscribe anytime.
By subscribing you agree we may email you about Ansible in a Minute and related Level Up Labs updates. We store your address in the same lead sheet as our contact form.
Request
loop server_configs dict2items and print key ip_address role
Example
A quick heads-up: Every environment is different. Review and test this example before you run it on systems you care about.
---
- name: Deploy server configurations
hosts: all
gather_facts: false
vars:
server_configs:
web_01:
ip_address: 10.1.1.50
role: frontend
db_01:
ip_address: 10.1.1.100
role: backend_db
tasks:
- name: Loop through server_configs
ansible.builtin.debug:
msg: "{{ item.key }} - IP: {{ item.value.ip_address }} - Role: {{ item.value.role }}"
loop: "{{ server_configs | dict2items }}"How it works
dict2items turns each dictionary entry into a list item with item.key and item.value. Nested fields are item.value.field.
When to use it
- Looping a mapping of hosts or services
- Replacing with_dict in new playbooks
Requirements
- Ansible: >=2.14
Validation
- Syntax validated
- Not execution-tested
- Last verified 2026-09-18
Notes
loop cannot iterate a raw dictionary. Use dict2items for key and value together. Use keys() | list when you only need the keys. dictsort is another replacement for with_dict.
Reference
- Iterating over a dictionary (Ansible docs)
Built for every Ansible use case in every organization
BacklogZero can generate this kind of automation in your environment, just like it did here.