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.
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
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_familyis "Debian". - The loop created three directories, reporting
changedfor each. - The
slurptask failed (file didn't exist), sorescueran and created a default file. - The
alwaysblock confirmed the file exists regardless of which path was taken. - The play recap shows
skipped=1andrescued=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: variableinstead ofwhen: variable is defined. If the variable doesn't exist, Ansible raises an undefined-variable error. Test withis definedfirst, or usedefault(). - Looping over packages instead of passing a list to
name:.loop:withaptcalls apt-get once per item. Passing a list toname:calls it once for all packages — much faster. - Ignoring the
changed_whendirective on command tasks.commandandshellalways reportchanged. Addchanged_when: falseto read-only commands (likelsorcat) so your play recap accurately reflects actual changes. - Catching too broadly with rescue. A
rescueblock catches any failure in itsblock, including genuine bugs. Keep block sections small and specific.
Key points
when:skips a task unless its Jinja2 condition is true; use Ansible facts likeansible_os_family.loop:repeats a task per item; forapt, passing a list toname:is faster than looping.register:captures task output; access.stdout,.rc,.stat.existsetc.block/rescue/alwaysprovides try/catch/finally error handling.until/retries/delaypolls until a condition is met — ideal for health checks after deploys.- Use
changed_when: falseon 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.