Ansible in a Minute · Ansible Core ·
Use when with loop to skip items
Short answer
Combine when with loop so Ansible tests the condition for each item and skips the rest.
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
print loop items only when the item is greater than 5
Example
A quick heads-up: Every environment is different. Review and test this example before you run it on systems you care about.
---
- name: Print loop items greater than 5
hosts: all
gather_facts: false
tasks:
- name: Print items greater than 5
ansible.builtin.debug:
msg: "{{ item }}"
loop:
- 0
- 2
- 4
- 6
- 8
- 10
when: item > 5How it works
when on a looped task is evaluated for each item. Ansible runs the task for matching items and skips the others. This play prints 6, 8, and 10.
When to use it
- Installing only packages that match a rule
- Skipping undefined or empty entries in a list
Requirements
- Ansible: >=2.14
Validation
- Syntax validated
- Not execution-tested
- Last verified 2026-09-22
Notes
If the loop variable may be undefined, use loop: "{{ mylist | default([]) }}" so the task does not fail. For a dictionary, loop query('dict', mydict | default({})) and test item.key or item.value.
Reference
- Using conditionals in loops (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.