Always trigger handler execution in Ansible

Solution 1:

If you absolutely need to trigger a handler every time then here are two options:

1) run a noop shell command which will always report as changed

-  name: trigger nginx-restart
   command: /bin/true
   notify: nginx-restart

2) use debug along with changed_when: to trigger a handler

-  debug: msg="trigger nginx-restart"
   notify: nginx-restart
   changed_when: true

Also of note for Option 1 and Check Mode: You may want to use check_mode: no if using Ansible version 2.2 or higher or always_run: yes if using earlier versions than that so that the task does not get skipped over in check mode. From my manual testing it looks like the handlers remain in check mode, but please be careful as your case may differ.

Solution 2:

Ansible provides several options for forcing handlers:

  1. To always force all handlers, run ansible-playbook playbook.yml --force-handlers, as documented here: https://github.com/ansible/ansible/issues/4777

  2. To force handlers that have been notified at a specific point within a playbook, you can use a meta task https://docs.ansible.com/playbooks_intro.html:

    tasks:

    • shell: some tasks go here
    • meta: flush_handlers
    • shell: some other tasks
  3. However, it sounds like you just want to make sure a service is running or restarted, regardless of the outcome of another task. In that case, don't use a handler, use a new task that calls Ansible's service module: https://docs.ansible.com/ansible/latest/collections/ansible/builtin/service_module.html

    tasks:

    • name: ensure ntp is running service: name=ntp state=started enabled=yes

    • name: always reload nginx service: name=nginx state=reloaded

    • name: always restart MySQL service: name=mysql state=restarted


Solution 3:

Restarting a service is one thing; ensuring it is running is another. If you want ansible to make sure nginx is running, you do this:

tasks:
  - name: Ensure nginx is running
    service: name=nginx state=started

Tags:

Ansible