Last Updated: February 25, 2016
· ramondelafuente

Adding hooks to your Ansible roles

When writing Ansible roles, it pays to leave room for inserting tasks (like callbacks or hooks).

For example, in [role]/tasks/main.yml:

- task 1
- task 2
   <--- you want to allow something to happen here.
- task 3

In order to do that, add an empty file in (for example)[role]/hooks/empty.yml, and add an insert statement like the following:

- include: "{{ hook_variable | default(lookup('pipe', 'pwd') ~ '/hooks/empty.yml') }}"

Where hook_variable is a full path to the tasks file to include.

An example that uses the playbook_dir:

hook_variable: "{{ playbook_dir }}/hooks/tasks-file.yml" 

The reason the default filter is used, is because it's required to point to an existing file with include. The above example uses the lookup plugin to find your role's path.