Handlers
Ansible modules are designed to be idempotent. This means that in a properly written playbook, the playbook and its tasks can be run multiple times without changing the managed host unless they need to make a change to get the managed host to the desired state.
Handlers are tasks that respond to a notification triggered by other tasks.
Handlers can be considered as inactive tasks that only get triggered when explicitly invoked using a notify
statement.
Example:
tasks:
- name: Copy configuration template
template:
src: /var/lib/templates/example.conf.template
dest: /etc/httpd/conf.d/example.conf
notify:
- restart apache
handlers:
- name: restart apache
service:
name: httpd
state: restarted
A task may call more than one handler in its notify
section.
Example:
- Handlers always run in the order specified by the handlers section of the play.
- Handlers normally run after all other tasks in the play complete.
- Handler names exist in a per-play namespace. If two handlers are incorrectly given the same name, only one will run.
- Even if more than one task notifies a handler, the handler only runs once.
- If a task that includes a notify statement does not report a changed result the handler is not notified.