Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 29 ยท Variables and Logic

Conditionals and Loops

Control which Ansible tasks run with when, repeat tasks over lists with loop, retry with until, and avoid the truthiness and registered-result pitfalls that trip up beginners.

Real servers differ. One runs Debian and another Red Hat, one has eight CPUs and another two, one already has the file you want to create. A playbook that treats them all identically either breaks or wastes time. Two keywords handle most of the variation: when decides whether a task runs on a host, and loop repeats a task for every item in a list.

You will learn the syntax of both, how they combine, how until retries a task that needs time to succeed, and the classic mistakes: quoting, truthiness and misreading registered results. This lesson builds on Variables, Facts and Precedence; the values tested in conditions are usually facts and registered variables.

Real Ansible needs servers, so the playbooks below are read-only. The runnable examples are JavaScript stand-ins that copy the decision logic. They are not Ansible's engine, and a JavaScript function is not a Jinja2 expression, but the control flow is the same.

when: run a task only if a condition holds

when takes a Jinja2 expression, written without braces. If it evaluates to true, the task runs; otherwise the host shows skipping for that task.

YAML
- hosts: all
  tasks:
    - name: Install nginx on Debian-like systems
      ansible.builtin.apt:
        name: nginx
        state: present
      when: ansible_facts['os_family'] == "Debian"

    - name: Install nginx on Red Hat-like systems
      ansible.builtin.dnf:
        name: nginx
        state: present
      when: ansible_facts['os_family'] == "RedHat"

You can use comparison operators (==, !=, >=, in), and, or, not, and tests such as is defined, is not defined, is success and is changed. A list under when means "all of these must be true":

YAML
      when:
        - ansible_facts['os_family'] == "Debian"
        - ansible_facts['processor_vcpus'] >= 4
        - app_env is defined

The most common mistake is wrapping the whole expression in {{ }}. Ansible already evaluates when as an expression, so write when: http_port == 80, not when: "{{ http_port == 80 }}". Another pitfall: a skipped task is not a failure, and later tasks still run. Use the facts and variables from the previous lesson to decide, and keep conditions short; if one grows long, compute it once with set_fact and test that variable.

Truthiness and booleans

YAML turns yes, no, on, off, true and false (case variants too) into booleans, and Ansible accepts them. But a value that arrives as a string (from -e, a lookup, or a quoted YAML value) is a string, and a non-empty string is not automatically a boolean. When in doubt, convert it with the bool filter:

YAML
- name: Run the migration only when asked
  ansible.builtin.command: /opt/app/migrate
  when: run_migrations | bool
Terminal
ansible-playbook site.yml -e "run_migrations=yes"

Other traps to know: comparing a number with a string ("8" == 8 is false), using when: var on a variable that might be undefined (add is defined or a default), and forgetting that when conditions on a registered result must look at a field (result.rc == 0), not at the whole result map.

Stand-in: when and loop together

The runner below evaluates a condition for each host-task-item combination and prints changed or skipping, the way Ansible's output does. Edit the facts to see the branches flip.

JS when and loop over items

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice the last task: when when and loop are combined, the condition is checked separately for each item. The loop variable is called item by default.

loop: repeat a task over a list

loop runs a task once per element. Inside the task, {{ item }} is the current element.

YAML
- name: Install several packages
  ansible.builtin.package:
    name: "{{ item }}"
    state: present
  loop:
    - git
    - curl
    - htop

- name: Create users with extra data
  ansible.builtin.user:
    name: "{{ item.name }}"
    groups: "{{ item.groups }}"
  loop:
    - { name: alice, groups: sudo }
    - { name: bob, groups: developers }

You can also loop over a list variable (loop: "{{ packages }}") or over a dictionary with the dict2items filter. Many modules accept a list directly (name: [git, curl, htop]), which is faster than looping because the package manager runs once. Prefer that when the module allows it.

Older playbooks use with_items, with_dict, with_fileglob and similar. These still work, but new code should use loop with a filter or lookup, because the syntax is one consistent thing to learn.

loop_control

loop_control adjusts how the loop behaves and how it prints.

YAML
- name: Create users quietly
  ansible.builtin.user:
    name: "{{ person.name }}"
  loop: "{{ team }}"
  loop_control:
    loop_var: person    # avoid clashing with an outer loop's `item`
    label: "{{ person.name }}"   # print only the name, not the whole map
    pause: 1            # wait a second between items

loop_var matters when a loop runs inside an included task file that is itself in a loop: both would use item. label keeps the output readable when items are large maps, and it also hides noisy or sensitive fields from the log (but not from a determined reader; use no_log for secrets, see Ansible Vault and Secrets).

Registered results in loops

When register is used on a looping task, the variable holds a map with a results list, one entry per item, each with the item's own changed, rc and so on.

YAML
- name: Check each service
  ansible.builtin.command: "systemctl is-active {{ item }}"
  loop: [nginx, ssh, cron]
  register: svc
  changed_when: false
  failed_when: false

- name: Report the inactive ones
  ansible.builtin.debug:
    msg: "{{ item.item }} is not active"
  loop: "{{ svc.results }}"
  when: item.rc != 0

Here item.item is the original loop element stored in each result. Looping over results and filtering with when is a very common pattern, and so is using a filter such as selectattr (covered in Jinja2 Templates and Filters).

until: retry until it works

Some tasks need time: a service that takes a moment to listen, an API that is not ready yet. until repeats a task until a condition is true, up to retries times, waiting delay seconds between attempts.

YAML
- name: Wait for the health endpoint
  ansible.builtin.uri:
    url: http://localhost:8080/health
    status_code: 200
  register: health
  until: health.status == 200
  retries: 10
  delay: 3

If every attempt fails, the task fails. The default is 3 retries with a 5-second delay. (For a plain "wait for a port" job, wait_for is simpler; see Services, Commands and Scheduling.)

flowchart TD
  A["Run the task"] --> B{"until condition true?"}
  B -- yes --> C["Task succeeds"]
  B -- no --> D{"retries left?"}
  D -- yes --> E["Wait delay seconds"]
  E --> A
  D -- no --> F["Task fails"]

An until loop runs the task, tests the condition, and retries after a delay until it succeeds or runs out of retries.

Stand-in: retries and the bool filter

The first half simulates a service that only becomes healthy on the fourth check. The second half is a small model of the bool filter from earlier: it treats a handful of words as true and everything else as false.

JS until, retries and truthiness

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Change retries to 3 to watch the task run out of attempts and fail.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which when line is written correctly?

    when already evaluates a Jinja2 expression, so you write it without braces. Wrapping it in {{ }} is the classic mistake.
  2. 2. A task has both loop and when: item.admin. How often is the condition evaluated?

    With loop, the condition is checked for every item, which is why the output can show some items as skipping and others as changed.
  3. 3. You register the result of a looping task. Where are the per-item results?

    A registered looping task has a results list, with one entry per item, each carrying its own rc, changed and the original item under .item.
  4. 4. What does until combined with retries: 10 and delay: 3 do?

    The task is retried with a delay between attempts until the until condition holds; if retries run out, the task fails.

Summary

  • when takes a Jinja2 expression without braces; a list means all conditions must hold.
  • Convert string values with | bool, and guard possibly undefined variables with is defined or default.
  • loop repeats a task once per item (item by default); prefer a module's own list support when it exists, and prefer loop over legacy with_*.
  • loop_control provides loop_var, label and pause.
  • Registered looping tasks store a results list; until, retries and delay retry a task that needs time.

Next: Jinja2 Templates and Filters.