A StackOverflow question showed me that Ansible handlers can be stored in their own YAML file and included into any playbook to avoid repetition. You can create a handler.yml
file that is just a list of handlers, like:
- name: restart apache
command: 'apachectl graceful'
listen: 'apache conf change'
- name: restart ssh
service:
name: ssh
state: restarted
Then, in any given playbook, you can include and use them like:
- name: my playbook
become: true
handlers:
- include: handlers.yml
hosts: all
tasks:
- name: configure server name
lineinfile:
dest: /etc/apache2/apache2.conf
line: 'ServerName tobymackenzie.com'
regexp: '^ServerName.*$'
state: present
notify: 'apache conf change'
This simplifies things nicely if you reuse handlers in multiple playbooks. Roles sound like they make this even easier, but I haven’t switched to them yet.