8

Is it possible to have truly global handlers in Ansible so that I can "notify" the handler from any task of any role of any playbook? And without explicitly importing.

I just want to define a handler once (say "restart httpd") and have it available to any "notify" directive anywhere.

Thanks!

2 Answers2

5

You could define your handlers within your play instead of within roles. Handlers defined in a play would be available to all tasks/roles under that play.

You are able to use import if you wanted in the handlers section too.

---
- hosts: all
  handlers:
  - import_tasks: global_handlers.yml
  tasks:
  - shell: echo "Hello World"
    notify: some thing from global_handlers

Note that you need a 'static include' (per https://docs.ansible.com/ansible/latest/user_guide/playbooks_intro.html#handlers-running-operations-on-change), so import_tasks must be used instead of include_tasks:

You cannot notify a handler that is defined inside of an include. As of Ansible 2.1, this does work, however the include must be static.

aidanhs
  • 5
  • 3
Zoredache
  • 130,897
  • 41
  • 276
  • 420
2

There is at least two ways to achieve this; and it's not clear to me what the best practice is.

Solution 1

One recommended practice is to create a file only for handlers, and include or import it in your playbook (see the differences); that way, all the roles can benefits.

For instance, let's say you have a file myhandlers.yml with inside one handler to restart apache, and another one to reload mysqld.

Then, in your playbook:

- name: Testing 123
  hosts: localhost
  handlers:
    - name: Here are my custom common handlers
      # You can also look at include_tasks: handlers.yml
      import_tasks: handlers.yml
  tasks:
    - command: "true"
      notify: restart-apache
    
    - command: "true"
      notify: restart-mysql

Solution 2

Another clean approach is to create a dedicated role (roles/myhandlers/ for instance), and make this role a depedencies for all the others roles.

dependencies:
  - myhandlers

More info on dependencies here.

4wk_
  • 310
  • 3
  • 15