Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 29 ยท Structuring Automation

Handlers, Tags and Task Control

Run Ansible actions only when something changed with handlers, select tasks with tags, handle failures with block/rescue/always, and control execution with delegate_to, run_once and serial.

A playbook that only lists tasks in order is fine for a demo. Real playbooks need finer control: restart nginx only if its config changed, run just the configuration tasks without reinstalling packages, roll back when a deployment step fails, update web servers two at a time so the site stays up. Ansible has a keyword for each of these: handlers, tags, block/rescue/always, and the execution controls delegate_to, run_once and serial.

This lesson explains each with a read-only playbook and then lets you experiment with JavaScript stand-ins that copy the semantics (notify once, tag selection, rescue flow). The stand-ins are not Ansible's engine; real Ansible needs servers and SSH, which this site cannot provide.

Handlers: react to change, once

Many actions only make sense after something changed: reload a service after its config file was rewritten, rebuild an index after new data arrived. A handler is a task that does not run on its own. Other tasks notify it, and it runs only if at least one notifying task reported changed.

YAML
- hosts: web
  tasks:
    - name: Write nginx.conf
      ansible.builtin.template:
        src: nginx.conf.j2
        dest: /etc/nginx/nginx.conf
      notify: Reload nginx

    - name: Write the site config
      ansible.builtin.template:
        src: site.conf.j2
        dest: /etc/nginx/conf.d/shop.conf
      notify: Reload nginx

  handlers:
    - name: Reload nginx
      ansible.builtin.service:
        name: nginx
        state: reloaded

Three rules define handler behavior:

  1. A handler runs at most once per host per play, no matter how many tasks notified it.
  2. Handlers run at the end of the play (after all tasks), in the order they are defined in the handlers section, not the order they were notified.
  3. A task that reports ok (no change) does not notify. So running the playbook again with no changes restarts nothing, which is exactly what idempotence should give you (see Modules and Idempotence).

If a task fails, the handlers notified earlier do not run by default and the play stops for that host. Use --force-handlers or force_handlers: true in the play to run them anyway.

Sometimes you need a handler now. meta: flush_handlers runs all pending handlers at that point:

YAML
    - name: Apply the new config before testing it
      ansible.builtin.meta: flush_handlers

    - name: Check the site answers
      ansible.builtin.uri:
        url: http://localhost/

listen: one notification, several handlers

A handler can listen to a topic name, so one notify triggers several handlers without the task knowing them:

YAML
  handlers:
    - name: Reload nginx
      ansible.builtin.service: { name: nginx, state: reloaded }
      listen: "web config changed"
    - name: Clear the page cache
      ansible.builtin.command: /usr/local/bin/clear-cache
      listen: "web config changed"

A task then says notify: "web config changed". This decouples tasks from handlers, which helps when handlers live in a role (see Roles and Project Layout).

Stand-in: notify once, run at the end

The model below runs three tasks. Two of them notify the same handler. Watch how many times the handler runs on the first and second pass.

JS Handlers run once, and only after a change

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

No output.

Pass { flushAfter: ["Write nginx.conf"] } as the fourth argument to runPlay to see what flush_handlers does: the handler runs early, and then again at the end only if something changed afterwards.

Tags: run part of a playbook

A tag is a label on a task, block, role or play. With --tags, only matching tasks run; with --skip-tags, matching tasks are left out.

YAML
- hosts: web
  tasks:
    - name: Install packages
      ansible.builtin.package: { name: nginx, state: present }
      tags: packages

    - name: Write config
      ansible.builtin.template: { src: nginx.conf.j2, dest: /etc/nginx/nginx.conf }
      tags: config

    - name: Smoke test
      ansible.builtin.uri: { url: "http://localhost/" }
      tags: [test, never]
Terminal
ansible-playbook site.yml --tags config          # only config tasks
ansible-playbook site.yml --skip-tags packages   # everything except packages
ansible-playbook site.yml --list-tags            # show the tags that exist
ansible-playbook site.yml --list-tasks           # show what would run

Two special tags exist. always runs every time, even when you select other tags (unless you skip it explicitly). never keeps a task out of normal runs; it only runs if you also select one of its other tags (here, --tags test). Tags on a role or an import_tasks apply to everything inside, while include_tasks needs apply: tags (see Roles and Project Layout for the import/include difference).

Failure handling

By default a failing task stops the play for that host while other hosts continue. You have several tools to change that.

  • ignore_errors: true continues after a failure but still reports it as failed in the recap. Use it sparingly.
  • failed_when and changed_when redefine what counts as failure or change from a result, such as a command's output (see Modules and Idempotence).
  • any_errors_fatal: true (on a play) stops all hosts when one fails, useful for coordinated changes.
  • max_fail_percentage aborts a rolling update when too many hosts have failed.

For try/catch-style logic, use block, rescue and always:

YAML
- name: Deploy with rollback
  block:
    - name: Unpack the new release
      ansible.builtin.unarchive: { src: app-2.tar.gz, dest: /srv/app/releases }
    - name: Switch the symlink
      ansible.builtin.file: { src: /srv/app/releases/2, dest: /srv/app/current, state: link }
  rescue:
    - name: Roll back to the previous release
      ansible.builtin.file: { src: /srv/app/releases/1, dest: /srv/app/current, state: link }
  always:
    - name: Record the attempt
      ansible.builtin.lineinfile: { path: /var/log/deploys.log, line: "deploy attempted", create: true }

If any task in block fails, the rescue tasks run, and the host then counts as recovered. The always section runs either way. A block can also carry shared keywords such as when, become or tags, so you write them once for a whole group of tasks.

Stand-in: tags and block/rescue/always

This model selects tasks by tag (including the special never behavior) and shows the order of block, rescue and always steps.

JS Tag selection and rescue flow

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

No output.

Try runBlock(1) to fail earlier: step 2 never happens, but rescue and always still do.

Controlling where and how many

Three keywords change where a task runs and how many hosts work at once.

  • delegate_to: host runs a task on a different machine while still using the current host's variables. The classic case: take a web server out of a load balancer (a task delegated to the balancer), update it, then put it back.
  • run_once: true runs a task a single time for the whole play (on the first host), such as a database migration. Its result is shared with every host.
  • serial limits how many hosts a play handles at a time. serial: 2 updates two servers, finishes them, then moves to the next two. It also accepts percentages and lists like [1, 5, "100%"] for a canary rollout.
YAML
- hosts: web
  serial: 2
  tasks:
    - name: Remove from the load balancer
      ansible.builtin.command: /usr/local/bin/lb-disable {{ inventory_hostname }}
      delegate_to: lb1

    - name: Update the app
      ansible.builtin.package: { name: myapp, state: latest }

    - name: Run the migration once
      ansible.builtin.command: /opt/myapp/migrate
      run_once: true

    - name: Add back to the load balancer
      ansible.builtin.command: /usr/local/bin/lb-enable {{ inventory_hostname }}
      delegate_to: lb1
flowchart TD
  T["Task changes a file"] -->|"changed + notify"| Q["Handler queue<br/>(no duplicates)"]
  T2["Another task changes a file"] -->|"changed + notify"| Q
  T3["Task reports ok"] -.->|"no notification"| Q
  Q --> E["End of play"]
  E --> H["Each notified handler runs once"]

Notifications collect in a queue without duplicates; handlers run once when the play's tasks are done.

Rolling updates are a theme in Ansible with Docker, Terraform and CI/CD, where serial batches protect a live service.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Three tasks each notify the handler Reload nginx, and all three report changed. How many times does the handler run on that host?

    Notifications are collected without duplicates and each handler runs at most once per host per play, after the tasks finish (unless flush_handlers is used).
  2. 2. What happens to a task tagged never when you run the playbook with no tag options?

    The special tag never keeps a task out of normal runs. Selecting another tag on the same task, for example --tags test, makes it run.
  3. 3. In a block/rescue/always structure, when does the always section run?

    always is like finally: it runs after the block and after any rescue tasks, regardless of the outcome.
  4. 4. You want to update web servers two at a time. Which keyword do you add to the play?

    serial sets the batch size for a play. forks is a global parallelism setting, and run_once runs a task a single time.

Summary

  • Handlers are tasks triggered by notify; they run once per host, at the end of the play, only after a change. flush_handlers runs them early; listen lets one topic trigger several.
  • Tags (--tags, --skip-tags, --list-tags) run part of a playbook; always and never are special.
  • block, rescue and always give try/catch/finally; ignore_errors, failed_when, any_errors_fatal and max_fail_percentage tune failure behavior.
  • delegate_to runs a task elsewhere, run_once runs it a single time, and serial updates hosts in batches.

Next: Roles and Project Layout.