Quiz Entry - updated: 2026.11.12
How can changed_when with a condition decide whether a handler gets notified?
Set it to a test on the registered output, for example "'Success' in command_result.stdout"; the task reports changed, and therefore notifies its handler, only when the test is true.
tasks:
- ansible.builtin.shell:
cmd: /usr/local/bin/upgrade-database
register: command_result
changed_when: "'Success' in command_result.stdout"
notify:
- restart_database
handlers:
- name: restart_database
ansible.builtin.service:
name: mariadb
state: restarted
The upgrade script runs on every play. If it actually upgraded something, it prints Success, the task reports changed, and the database restart is queued. If there was nothing to upgrade, the task reports ok and MariaDB keeps running.
This links two ideas from earlier: handlers fire only on changed, and changed_when lets you define what changed means. Together they turn a non-idempotent script into a task that follows Ansible's change model.
Go deeper:
Defining when tasks change (official docs) โ
changed_whenused to control handler notification.