Introduction to Ansible ANSIBLE Course · Practical Exercises + MCQs · 15/01/2026
Chapter 07 · Advanced Playbooks

Advanced Playbooks

Playbook objectives (before writing)

  • Define the target state and constraints (SLA, security, downtime).
  • Identify the variables (environment, versions, secrets).
  • Define the execution strategy (batches, rolling updates).
  • Plan verification (health checks, tests, handlers, retries).
Tip: a playbook without an objective is like a novel without a plot. It can exist, but it is frustrating.

Variables at multiple levels

Ansible resolves variables according to precedence (which value wins when there is a conflict). Without going through an endless list, remember:

  • You can define variables in the inventory, in group_vars/, host_vars/, in roles, in the playbook, or as extra variables (-e).
  • -e (extra variables) take precedence: useful, but risky if overused.

Useful advanced patterns

  • register + until/retries/delay to wait for a service.
  • block/rescue/always to handle errors cleanly.
  • delegation (delegate_to) to run a task on another host.
  • run_once for one-off actions (database migrations, etc.).
- name: Wait for port 80 to respond
  ansible.builtin.uri:
    url: "http://localhost"
    status_code: 200
  register: health
  until: health.status == 200
  retries: 10
  delay: 2

Delegation: running a task on another host (delegate_to)

Normally, Ansible runs a task on the host currently being processed by the play. The delegate_to keyword changes where that particular task runs, without changing the host to which the play belongs.

Typical uses: check a website from the control node, contact a load balancer, or perform an action on a central monitoring server.

Demonstration 1: compare a normal task with a delegated task

Create delegation.yml. The first command runs on each managed host; the second runs on the Ansible control node. Both tasks still belong to the current inventory host.

---
- name: Discover where tasks run
  hosts: web
  gather_facts: false

  tasks:
    - name: Run hostname on the managed host
      ansible.builtin.command: hostname
      register: remote_name
      changed_when: false

    - name: Run hostname on the control node
      ansible.builtin.command: hostname
      delegate_to: localhost
      register: control_name
      changed_when: false

    - name: Compare both results
      ansible.builtin.debug:
        msg:
          - "Inventory host: {{ inventory_hostname }}"
          - "Managed host reports: {{ remote_name.stdout }}"
          - "Control node reports: {{ control_name.stdout }}"

Run:

ansible-playbook -i inventory.ini delegation.yml

Observe: the delegated task is displayed with an arrow, such as deb-01 -> localhost. If your inventory names are aliases, inventory_hostname may differ from the hostname returned by the operating system.

Important: delegate_to: localhost means the control node in this example. It does not mean the remote machine's localhost. Also, delegation does not automatically make a task run only once: with two web hosts, the delegated task normally runs twice.

Demonstration 2: check each web server from the control node

This is a realistic health check. Unlike a check against 127.0.0.1 on each server, it verifies that the web service is reachable from the controller. The web servers must already be running and reachable over HTTP.

---
- name: Check web servers from the controller
  hosts: web
  gather_facts: false

  tasks:
    - name: Check the HTTP endpoint externally
      ansible.builtin.uri:
        url: "http://{{ ansible_host | default(inventory_hostname) }}/"
        status_code: 200
        return_content: false
        timeout: 5
      delegate_to: localhost
      register: external_check

    - name: Display the HTTP status
      ansible.builtin.debug:
        msg: "{{ inventory_hostname }} returned HTTP {{ external_check.status }}"
Teaching point: the HTTP request is made by the controller, but external_check is registered against the original inventory host. Use ansible_host | default(inventory_hostname) to address the server rather than the controller.

Practical challenge: a one-off delegated action

Add a task that writes a deployment note on the control node. Combine delegate_to: localhost with run_once: true so that the task is not repeated for every web host (for a play without serial).

- name: Write one deployment note on the controller
  ansible.builtin.copy:
    dest: /tmp/ansible-deployment-note.txt
    content: "Web deployment initiated by Ansible.\n"
    mode: "0644"
  delegate_to: localhost
  run_once: true
With serial: run_once is evaluated once per batch, not necessarily once for the entire play. For an action that must happen exactly once overall, use a separate play targeting localhost, or carefully control the condition.

Error handling: block, rescue and always

These keywords group tasks and provide structured error handling. They resemble try / except / finally in Python, although their behaviour is specific to Ansible.

KeywordPurposeWhen it runs
blockGroups the normal tasksFirst
rescueHandles a failed task in the blockOnly when a task in the block fails
alwaysPerforms clean-up or reportingAfter the block, whether it succeeds or fails

Demonstration 3: force an error and observe the execution order

Create block-demo.yml. Change the variable simulate_failure to switch between success and failure. No package installation or administrator rights are required.

---
- name: Demonstrate block, rescue and always
  hosts: all
  gather_facts: false

  vars:
    simulate_failure: true

  tasks:
    - name: Test structured error handling
      block:
        - name: START - enter the block
          ansible.builtin.debug:
            msg: "START on {{ inventory_hostname }}"

        - name: Simulate a failure
          ansible.builtin.fail:
            msg: "Simulated deployment error"
          when: simulate_failure | bool

        - name: Confirm that the block completed
          ansible.builtin.debug:
            msg: "BLOCK SUCCESS on {{ inventory_hostname }}"

      rescue:
        - name: Explain what failed
          ansible.builtin.debug:
            msg:
              - "RESCUE on {{ inventory_hostname }}"
              - "Failed task: {{ ansible_failed_task.name }}"
              - "Reason: {{ ansible_failed_result.msg }}"

      always:
        - name: Display the final message
          ansible.builtin.debug:
            msg: "ALWAYS on {{ inventory_hostname }}"

Execute the playbook:

ansible-playbook -i inventory.ini block-demo.yml

Expected sequence with simulate_failure: true: START → simulated failure → RESCUE → ALWAYS. The “BLOCK SUCCESS” task is skipped because execution leaves the block after the failure.

Change the variable to false and run it again. The sequence becomes START → BLOCK SUCCESS → ALWAYS; the rescue tasks do not run.

Key detail: if rescue succeeds, Ansible considers the original failure handled and the play can continue. To preserve a failed result, explicitly use ansible.builtin.fail in rescue, as the existing rolling-update example does.

Demonstration 4: a practical deployment with diagnostics and clean-up

The following pattern tests a service, displays useful information on failure, and reports completion in all cases. It assumes nginx is already installed on Debian/Ubuntu managed hosts.

---
- name: Verify nginx with structured error handling
  hosts: web
  become: true
  gather_facts: false

  tasks:
    - name: Verify and report
      block:
        - name: Ensure nginx is running
          ansible.builtin.service:
            name: nginx
            state: started

        - name: Check HTTP locally on the managed host
          ansible.builtin.uri:
            url: http://127.0.0.1/
            status_code: 200

      rescue:
        - name: Collect nginx service diagnostics
          ansible.builtin.command: systemctl status nginx --no-pager
          register: nginx_diagnostics
          changed_when: false
          failed_when: false

        - name: Show the diagnostics
          ansible.builtin.debug:
            var: nginx_diagnostics.stdout_lines

        - name: Report the deployment failure
          ansible.builtin.fail:
            msg: "nginx verification failed on {{ inventory_hostname }}"

      always:
        - name: Display completion notice
          ansible.builtin.debug:
            msg: "Verification attempt finished on {{ inventory_hostname }}"
Limits: rescue handles tasks that return a failed result. It does not recover from unreachable hosts or invalid task definitions. always runs for hosts still able to execute tasks, not magically for disconnected machines.

Practical exercise: combine delegation with error handling

  1. Run the external HTTP health check from localhost using delegate_to.
  2. Place the check inside a block.
  3. In rescue, display the name of the host that failed and the Ansible error message.
  4. In always, display a completion message for the current host.
  5. Stop nginx on one managed host and observe the difference between the two hosts; restart it afterwards.
Suggested solution
---
- name: External check with error handling
  hosts: web
  gather_facts: false

  tasks:
    - name: Check the web server
      block:
        - name: Request the home page from the controller
          ansible.builtin.uri:
            url: "http://{{ ansible_host | default(inventory_hostname) }}/"
            status_code: 200
            timeout: 5
          delegate_to: localhost

      rescue:
        - name: Display the error
          ansible.builtin.debug:
            msg: "{{ inventory_hostname }} failed: {{ ansible_failed_result.msg }}"

        - name: Keep the host marked as failed
          ansible.builtin.fail:
            msg: "External health check failed for {{ inventory_hostname }}"

      always:
        - name: Confirm that the check was attempted
          ansible.builtin.debug:
            msg: "Check finished for {{ inventory_hostname }}"

Practical exercise: rolling update + health check

  1. Add serial: 1 to your web play.
  2. After deployment, perform an HTTP health check using uri.
  3. If the health check fails, fail the play (this is already the default behaviour).
  4. Add a block/rescue that logs a diagnostic message.
Minimal example
- name: Rolling update with health check
  hosts: web
  become: true
  serial: 1

  vars:
    index_msg: "Hello from Ansible (chapter 7)"

  tasks:
    - name: Deployment and verification
      block:
        - name: Install nginx
          ansible.builtin.apt:
            name: nginx
            state: present
            update_cache: true
          tags: [install]

        - name: Deploy the home page
          ansible.builtin.copy:
            dest: /var/www/html/index.html
            content: "<h1>{{ index_msg }}</h1>\n"
            owner: root
            group: root
            mode: "0644"
          notify: restart nginx
          tags: [config]

        - name: Start and enable nginx
          ansible.builtin.service:
            name: nginx
            state: started
            enabled: true
          tags: [service]

        - name: Run the handlers now
          ansible.builtin.meta: flush_handlers

        - name: HTTP health check (wait for a response)
          ansible.builtin.uri:
            url: "http://127.0.0.1/"
            status_code: 200
            return_content: false
          register: health
          until: health.status == 200
          retries: 10
          delay: 2
          tags: [verify]

      rescue:
        - name: nginx systemd diagnostics
          ansible.builtin.command: systemctl status nginx --no-pager
          register: nginx_status
          changed_when: false
          failed_when: false

        - name: Display diagnostics
          ansible.builtin.debug:
            var: nginx_status.stdout_lines

        - name: Explicitly fail the play on this host
          ansible.builtin.fail:
            msg: "Health check failed on {{ inventory_hostname }}. See diagnostics above."

  handlers:
    - name: restart nginx
      ansible.builtin.service:
        name: nginx
        state: restarted

    

Additional questions: delegation and error handling

1) What does delegate_to: localhost do?
  • A. Runs the task on the control node
  • B. Runs the whole play on the control node
  • C. Renames the inventory host
2) When does rescue run?
  • A. After every task
  • B. When a task in its block fails
  • C. Only when the playbook starts
3) When does always run?
  • A. After the block, whether it succeeded or failed
  • B. Only after a successful block
  • C. Only after a failed block
4) Does run_once: true with serial always mean once for the entire play?
  • A. Yes
  • B. No, it may run once per batch
Answer key
1) A · 2) B · 3) A · 4) B

Multiple-choice quiz

1) serial: 1 means:
  • A. Execution one host at a time
  • B. Faster execution
  • C. Disabling handlers
2) until/retries/delay is used to:
  • A. Run a conditional retry loop
  • B. Encrypt files
  • C. Update Git
3) Variables can be overridden by:
  • A. group_vars/host_vars
  • B. extra-vars (-e)
  • C. Both A and B
Answer key
1) A · 2) A · 3) C