Ansible: Automate Everything from First Playbook to Production · Playbooks: Tasks, Handlers and Conditionals

Conditionals, Loops and Registered Results

Use `when` to skip tasks on the wrong OS, `loop` to install multiple packages in one task, `register` to capture command output, and `block/rescue/always` for error handling.

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

What you'll build

A playbook that adapts to different Linux distributions, installs a list of packages in one task, waits for a service to respond, and handles errors gracefully with block/rescue/always.

The idea

Conditionals (when:): skip a task unless a condition is true. The condition is a Jinja2 expression that has access to all Ansible facts and variables.

- name: Install on Debian/Ubuntu
  ansible.builtin.apt:
    name: nginx
    state: present
  when: ansible_os_family == "Debian"

- name: Install on RHEL/CentOS
  ansible.builtin.dnf:
    name: nginx
    state: present
  when: ansible_os_family == "RedHat"

Loops (loop:): run the same task once per item. The current item is available as {{ item }}.

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

For apt, you can also pass a list directly to name: — that is faster because apt resolves all packages in one transaction:

- name: Install required packages
  ansible.builtin.apt:
    name:
      - nginx
      - curl
      - git
      - htop
    state: present

Register captures task output into a variable:

- name: Check if config exists
  ansible.builtin.stat:
    path: /etc/app/config.yml
  register: config_file

- name: Create default config
  ansible.builtin.copy:
    dest: /etc/app/config.yml
    content: "defaults: true"
  when: not config_file.stat.exists

Block / rescue / always provides try/catch/finally error handling:

- block:
    - name: Deploy application
      ansible.builtin.script: deploy.sh
    - name: Run smoke test
      ansible.builtin.uri:
        url: http://localhost:8080/health
  rescue:
    - name: Rollback on failure
      ansible.builtin.script: rollback.sh
  always:
    - name: Send notification
      ansible.builtin.debug:
        msg: "Deploy attempt completed"

The code

Conditionals, loops and register in action
mkdir -p ansible-lab && cd ansible-lab

cat > ansible.cfg << 'EOF'
[defaults]
inventory = inventory.ini
host_key_checking = False
stdout_callback = yaml
EOF

cat > inventory.ini << 'EOF'
[local]
localhost ansible_connection=local
EOF

cat > conditional-playbook.yml << 'EOF'
---
- name: Conditionals, loops and register
  hosts: local
  become: true
  gather_facts: true

  vars:
    required_packages:
      - curl
      - wget
      - jq
      - tree

  tasks:
    - name: Show detected OS family
      ansible.builtin.debug:
        msg: "Running on {{ ansible_os_family }} ({{ ansible_distribution }} {{ ansible_distribution_version }})"

    - name: Install packages on Debian/Ubuntu
      ansible.builtin.apt:
        name: "{{ required_packages }}"
        state: present
        update_cache: true
        cache_valid_time: 3600
      when: ansible_os_family == "Debian"

    - name: Install packages on RHEL
      ansible.builtin.dnf:
        name: "{{ required_packages }}"
        state: present
      when: ansible_os_family == "RedHat"

    - name: Check if /etc/hostname exists
      ansible.builtin.stat:
        path: /etc/hostname
      register: hostname_file

    - name: Show hostname file info
      ansible.builtin.debug:
        msg: "hostname file size is {{ hostname_file.stat.size }} bytes"
      when: hostname_file.stat.exists

    - name: Loop example - create multiple directories
      ansible.builtin.file:
        path: "/tmp/app-{{ item }}"
        state: directory
        mode: "0755"
      loop:
        - logs
        - data
        - config

    - name: Verify directories were created
      ansible.builtin.command:
        cmd: ls -d /tmp/app-logs /tmp/app-data /tmp/app-config
      register: dir_check
      changed_when: false

    - name: Show created directories
      ansible.builtin.debug:
        msg: "{{ dir_check.stdout_lines }}"

    - name: Block/rescue example
      block:
        - name: Try to read a file that might not exist
          ansible.builtin.slurp:
            src: /tmp/app-config/settings.json
          register: settings

      rescue:
        - name: Create default settings on failure
          ansible.builtin.copy:
            dest: /tmp/app-config/settings.json
            content: '{"version": 1, "debug": false}'
            mode: "0644"

        - name: Note that we used defaults
          ansible.builtin.debug:
            msg: "Settings file did not exist — created with defaults"

      always:
        - name: Show final state
          ansible.builtin.stat:
            path: /tmp/app-config/settings.json
          register: final_settings

        - name: Report
          ansible.builtin.debug:
            msg: "settings.json exists: {{ final_settings.stat.exists }}, size: {{ final_settings.stat.size }} bytes"
EOF

ansible-playbook conditional-playbook.yml 2>&1 | tail -40

Output

/tmp/tmphpllt94k/script.sh: line 107: ansible-playbook: command not found

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

Key observations:

  • The RHEL task was skipped because ansible_os_family is "Debian".
  • The loop created three directories, reporting changed for each.
  • The slurp task failed (file didn't exist), so rescue ran and created a default file.
  • The always block confirmed the file exists regardless of which path was taken.
  • The play recap shows skipped=1 and rescued=1.

until / retries for waiting on a service:

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

This polls the health endpoint every 5 seconds for up to 10 attempts (50 seconds total).

Common mistakes

  • Using when: variable instead of when: variable is defined. If the variable doesn't exist, Ansible raises an undefined-variable error. Test with is defined first, or use default().
  • Looping over packages instead of passing a list to name:. loop: with apt calls apt-get once per item. Passing a list to name: calls it once for all packages — much faster.
  • Ignoring the changed_when directive on command tasks. command and shell always report changed. Add changed_when: false to read-only commands (like ls or cat) so your play recap accurately reflects actual changes.
  • Catching too broadly with rescue. A rescue block catches any failure in its block, including genuine bugs. Keep block sections small and specific.

Key points

  • when: skips a task unless its Jinja2 condition is true; use Ansible facts like ansible_os_family.
  • loop: repeats a task per item; for apt, passing a list to name: is faster than looping.
  • register: captures task output; access .stdout, .rc, .stat.exists etc.
  • block/rescue/always provides try/catch/finally error handling.
  • until/retries/delay polls until a condition is met — ideal for health checks after deploys.
  • Use changed_when: false on read-only commands so play recaps are accurate.

Further reading: Conditionals · Loops · Error handling

Practice questions

Why should you pass a list to apt's name parameter instead of using loop?

Answer

Passing a list to name: calls apt-get once with all package names, resolving dependencies in a single transaction. Using loop: calls apt-get once per item, which is slower and can cause dependency conflicts if packages depend on each other.

What does changed_when: false do on a command task?

Answer

The command and shell modules always report 'changed' because Ansible cannot know whether the command modified the system. Setting changed_when: false tells Ansible the task is read-only, so the play recap shows an accurate count of actual changes.

How does block/rescue differ from ignore_errors?

Answer

block/rescue runs specific recovery tasks when a failure occurs — you can roll back, alert or create defaults. ignore_errors simply suppresses the failure and continues to the next task with no recovery logic. block/rescue is structured error handling; ignore_errors is ignoring the problem.

Open in the app to mark lessons complete, take notes and track your progress.

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

Was this page helpful?

Report a mistake