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.
Written by Ramon de la Fuente
Related protips
1 Response
Excellent idea. My approach was to have only the variable in the include statement, no default, and then instead have a when condition to enable the inclusion only when the variable is defined. This hook in our generic deployment flow saved the day for one of my colleagues today.
- name: Run tasks pointed at by pre_start_hook if defined
include: "{{ pre_start_hook }}"
when: pre_start_hook is defined