BacklogZero®

Ansible in a Minute · Ansible Core ·

Use break_when to stop a loop

Short answer

Set loop_control break_when so Ansible exits the loop after the item that matches the condition.

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 1 through 5 with debug and stop the loop when item is 3 using break_when

Example

A quick heads-up: Every environment is different. Review and test this example before you run it on systems you care about.

YAML
---
# Prompt: loop 1 through 5 with debug and stop the loop when item is 3 using break_when
- name: Stop the loop when item is 3
  hosts: all
  gather_facts: false
  tasks:
    - name: Loop through items 1 to 5
      ansible.builtin.debug:
        msg: "{{ item }}"
      loop: [1, 2, 3, 4, 5]
      loop_control:
        break_when: item == 3

How it works

break_when is evaluated after each item. This task prints 1, 2, and 3, then stops. Items 4 and 5 do not run.

When to use it

  • Stopping after the first match in a list
  • Ending retries inside one looped task

Requirements

  • Ansible: >=2.18

Validation

  • Syntax validated
  • Not execution-tested
  • Last verified 2026-10-02

Notes

when skips an item and continues the loop. break_when ends the loop. Added in Ansible 2.18. You can pass a list of conditions. Every condition must be true to break.

Reference

Built for every Ansible use case in every organization

BacklogZero can generate this kind of automation in your environment, just like it did here.

Get BacklogZero today →

Related guides

← Back to Ansible in a Minute

Use break_when to stop a loop · Level Up Labs