Ansible Loops & Control Prompt
Use Ansible loops correctly — loop vs with_items, complex loops, retries, loop_var, nested loops, performance.
- Target user
- Ansible engineers iterating over data
- Difficulty
- Intermediate
- Tools
- Claude, ChatGPT
The prompt
You are a senior Ansible engineer who has refactored loops countless times — from old `with_*` to modern `loop`, complex item handling, retry logic.
I will provide:
- The loop in question
- Use case
- Symptom (slow, wrong values, can't iterate)
Your job:
1. **Modern loop syntax**:
- `loop:` — simple list
- `with_items` — legacy; use loop
- `with_dict`, `with_subelements`, etc. — replaced by loop + filters
2. **For loop variable**:
- Default: `item`
- Customize: `loop_control: loop_var: <name>`
- Critical when nested
3. **For complex iteration**:
- List of dicts: `loop: [{name: a, port: 80}, ...]`
- Access: `{{ item.name }}`
- Generate from data: `loop: "{{ users | dict2items }}"`
4. **For retry**:
- `until: condition`
- `retries: N`
- `delay: seconds`
5. **For nested**:
- `loop` + `with_subelements` (or `loop` + `product` filter)
- Use distinct loop_var
6. **For limit / skip**:
- `when: condition`
- Filter list before loop: `loop: "{{ items | selectattr('enabled') | list }}"`
7. **For performance**:
- One module call per iteration
- For modules supporting list (yum, apt) → pass list directly
- Massive speedup
8. **For loop_control**:
- `pause: N` between iterations
- `index_var:` for index
- `label:` for cleaner output
Mark DESTRUCTIVE: large loop without batching (timeout), nested loop variable collision, retry without backoff (storm), loop modifying critical config.
---
Loop: [PASTE]
Use case: [DESCRIBE]
Symptom: [DESCRIBE]
Why this prompt works
Loops are common but have pitfalls. This prompt walks them.
How to use it
- Use
loop:(modern). - Batch when module supports.
- Use distinct loop_var when nested.
- Retry with delay.
Patterns
Simple loop
- name: Install packages
package:
name: "{{ item }}"
state: present
loop:
- nginx
- postgresql
- redis
Batch (much faster — one apt/yum invocation)
- name: Install packages (batched)
package:
name:
- nginx
- postgresql
- redis
state: present
Loop over list of dicts
- name: Create users
user:
name: "{{ item.name }}"
uid: "{{ item.uid }}"
groups: "{{ item.groups }}"
loop:
- { name: alice, uid: 1001, groups: 'docker,wheel' }
- { name: bob, uid: 1002, groups: 'docker' }
Filter before loop
- name: Install only enabled services
service:
name: "{{ item.name }}"
state: started
enabled: yes
loop: "{{ services | selectattr('enabled', 'eq', true) | list }}"
loop_control:
label: "{{ item.name }}" # cleaner output
Nested with distinct loop_var
- name: Create users in groups
user:
name: "{{ user_item.name }}"
groups: "{{ group_item }}"
loop: "{{ users }}"
loop_control:
loop_var: user_item
vars:
group_item: "{{ user_item.group }}"
For real nested (product filter):
- name: Place file in each dir for each user
copy:
src: "{{ item[0] }}/{{ item[1].name }}"
dest: "/etc/users/{{ item[1].name }}/{{ item[0] }}"
loop: "{{ ['app1', 'app2'] | product(users) | list }}"
Retry with backoff
- name: Wait for API
uri:
url: https://api.example.com/health
register: api_response
until: api_response.status == 200
retries: 10
delay: 30
Loop control
- name: Process items with pause
shell: ./process.sh {{ item }}
loop: "{{ huge_list }}"
loop_control:
pause: 2 # 2s between iterations
index_var: idx
label: "Item {{ idx }}/{{ huge_list | length }}"
Common findings this catches
- Loop slow → batch via module list support.
- Nested clash → distinct loop_var.
- Retry no delay → adds delay.
- Wrong item structure → debug: var=item to inspect.
- with_items deprecated warning → migrate to loop.
- Output noise → loop_control: label.
- Loop fails part-way → use
failed_when: falseif expected.
When to escalate
- Performance issues at scale — batch design.
- Complex iteration patterns — refactor.
- Custom loop plugins — engineering.
Related prompts
-
Ansible Jinja2 Templates Advanced Patterns Prompt
Use advanced Jinja2 in Ansible — filters (default, map, selectattr), lookups, complex conditionals, custom filters.
-
Ansible Performance Tuning Prompt
Speed up Ansible playbooks — forks, pipelining, async, smart gathering, fact caching, mitogen.
-
Ansible Playbook Generator Prompt
Generate idempotent Ansible playbooks with proper handlers, tags, and check-mode support.