Ansible Tutorial · Playbooks · Lesson 10 of 20

Ansible Conditionals and Loops

Control task execution with when, loop, block and rescue.

Members can save this page, take notes and track progress. See membership · Sign in

when — conditional execution

The when keyword skips a task if the condition is false:

- name: Install apt packages (Debian/Ubuntu only)
  ansible.builtin.apt:
    name: nginx
    state: present
  when: ansible_os_family == "Debian"

- name: Install yum packages (RedHat only)
  ansible.builtin.dnf:
    name: httpd
    state: present
  when: ansible_os_family == "RedHat"

Conditions are Jinja2 expressions. You do not need {{ }} inside when — it is already evaluated as an expression.

Common conditions

when: ansible_distribution == "Ubuntu"
when: ansible_memtotal_mb > 2048
when: app_env == "production"
when: result.rc != 0
when: my_list | length > 0
when: my_var is defined
when: my_var is not defined

Combining conditions

when: ansible_os_family == "Debian" and ansible_distribution_version is version("22.04", ">=")
when: deploy_mode == "blue_green" or deploy_mode == "canary"

loop — iterate over a list

- name: Install multiple packages
  ansible.builtin.apt:
    name: "{{ item }}"
    state: present
  loop:
    - nginx
    - curl
    - htop
    - git

The special variable {{ item }} holds the current element.

Loop over dictionaries

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

until / retries — retry until a condition is met

- name: Wait for the app to respond
  ansible.builtin.uri:
    url: http://localhost:8080/health
    status_code: 200
  register: health
  until: health.status == 200
  retries: 10
  delay: 5

Ansible retries the task up to 10 times, waiting 5 seconds between attempts.

block / rescue / always — error handling

- name: Deploy with rollback
  block:
    - name: Pull latest code
      ansible.builtin.git:
        repo: https://github.com/org/app.git
        dest: /var/www/app
        version: "{{ release_tag }}"

    - name: Run migrations
      ansible.builtin.command: python manage.py migrate
      args:
        chdir: /var/www/app

  rescue:
    - name: Rollback to previous version
      ansible.builtin.git:
        repo: https://github.com/org/app.git
        dest: /var/www/app
        version: "{{ previous_tag }}"

    - name: Alert the team
      ansible.builtin.debug:
        msg: "Deploy of {{ release_tag }} failed, rolled back to {{ previous_tag }}"

  always:
    - name: Restart the app
      ansible.builtin.service:
        name: app
        state: restarted
  • block: the tasks to attempt.
  • rescue: runs only if a task in the block fails.
  • always: runs regardless of success or failure (like finally in Python).
Loop over a list
cat > /tmp/loop_demo.yml << 'EOF'
---
- name: Loop demo
  hosts: localhost
  connection: local
  gather_facts: false
  tasks:
    - name: Show each item
      ansible.builtin.debug:
        msg: "Package: {{ item }}"
      loop:
        - nginx
        - curl
        - git
EOF
ansible-playbook /tmp/loop_demo.yml

Output

PLAY [Loop demo] **************************************************************

TASK [Show each item] *********************************************************
ok: [localhost] => (item=nginx) => {
    "msg": "Package: nginx"
}
ok: [localhost] => (item=curl) => {
    "msg": "Package: curl"
}
ok: [localhost] => (item=git) => {
    "msg": "Package: git"
}

PLAY RECAP ********************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Run this on your computer — see “Get Started” for setup.

Conditional execution with when
cat > /tmp/when_demo.yml << 'EOF'
---
- name: Conditional demo
  hosts: localhost
  connection: local
  gather_facts: true
  tasks:
    - name: Only on Linux
      ansible.builtin.debug:
        msg: "This is a Linux system"
      when: ansible_system == "Linux"
    - name: Only on macOS
      ansible.builtin.debug:
        msg: "This is macOS"
      when: ansible_system == "Darwin"
EOF
ansible-playbook /tmp/when_demo.yml

Output

PLAY [Conditional demo] *******************************************************

TASK [Gathering Facts] ********************************************************
ok: [localhost]

TASK [Only on Linux] **********************************************************
ok: [localhost] => {
    "msg": "This is a Linux system"
}

TASK [Only on macOS] **********************************************************
skipping: [localhost]

PLAY RECAP ********************************************************************
localhost                  : ok=2    changed=0    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0

Run this on your computer — see “Get Started” for setup.

Test yourself

What runs if a task inside a 'block' fails?

  1. The play stops immediately
  2. The 'rescue' section runs
  3. The 'always' section runs
  4. Both rescue and always run
Show answer

Answer: Both rescue and always run

When a block task fails, the rescue section runs first, then the always section runs regardless of outcome (like try/except/finally in Python).

Last reviewed · By the ByteCamel team · How we write content

Was this page helpful?

Report a mistake