Sunday, 30 November 2025

Ansible- 10 handler

[oracle@oel01db playbooks]$ cat nginx

---

- name: Install and configure Nginx using yum

  hosts: webservers

  gather_facts: no

  become: yes               # elevate to root

  become_user: root         # optional (default = root)


  tasks:


    - name: Install Nginx using yum

      yum:

        name: nginx

        state: latest


    - name: Copy index.html

      template:

        src: index.html

        dest: /usr/share/nginx/html/index.html

        owner: nginx

        group: nginx

        mode: '0644'


    - name: Copy updated.html

      template:

        src: updated.html

        dest: /usr/share/nginx/html/index.html

        owner: nginx

        group: nginx

        mode: '0644'

      notify:

        - Restart Nginx


  handlers:

    - name: Restart Nginx

      service:

        name: nginx

        state: restarted


[oracle@oel01db playbooks]$


1. Do handlers run only when a task changes?

Yes.
Handlers run only when a task notifies them, and a task notifies only when:

✔ The task reports changed: true
❌ Not when ok: true
❌ Not when skipped
❌ Not when failed


notify:

  - Restart Nginx

This handler will run only when the template task actually changes the file.


.


🧪 Example

First run

updated.html is copied (file content changes) → task changes → handler runs → Nginx restarts

Second run

File content is same, no changes → changed: falsehandler will NOT run

Ansible handler runs ONLY if the task with notify changes.

Task 3 (Copy updated.html)

This one has:

notify: - Restart Nginx

So only this task can trigger the handler.

No comments:

Post a Comment

Building a Safer PostgreSQL CI/CD Pipeline with GitHub Actions: Dev → PR Review → Test Promotion

In my previous post, we explored a simple push-to-main deployment strategy . While functional, that model is not considered an industry best...