Introduction to Ansible Callback Plugin
Among Ansible plugins, this post covers only the Callback Plugin. A Callback Plugin is a module used for all sorts of purposes when a specific event happens in Ansible, such as logging data or writing to external channels like Slack or Mail. For reference, this was written against Ansible 2.2.1.0.
Introduction
An Ansible Callback Plugin is a plugin that hooks into Ansible’s various events so you can run your own logic at that point. It lets you define callback functions for events such as “right before execution” and “execution finished” on Ansible Tasks, Playbooks, and so on.
By default, callback functions only run for plugins registered in the callback_whitelist Ansible setting. This doesn’t apply if the callback module sets CALLBACK_NEEDS_WHITELIST = False.
Also, Callback Plugins run in alphanumeric order. (e.g. 1.py → 2.py → a.py) The order of the callback list in the configuration doesn’t matter.
Configuration
Here are the Ansible settings for using Callback Plugins. You can define them in ansible.cfg or pass them on the command line.
- callback_plugins : The directory where callback plugins live.
(ex) callback_plugins = ~/.ansible/plugins/callback:/usr/share/ansible/plugins/callback
- stdout_callback : Changes the default callback for stdout. Only callback plugin modules with CALLBACK_TYPE = stdout can be set here.
(ex) stdout_callback = skippy
- callback_whitelist : Names of the plugins whose callbacks should run. Callback plugin modules with CALLBACK_NEEDS_WHITELIST = False are not affected.
(ex) callback_whitelist = timer,mail
Event Hooking
The public methods of the CallbackBase class in “lib/ansible/plugins/callback/__init__.py” of the Ansible project are the callback functions you can hook events with.
To implement a Callback Plugin, inherit the CallbackBase class and override the events you want to use. If you want your callbacks to run only for Ansible 2.0+ events, override the methods with the “v2_” prefix.
| |
Implementation Example
First, note that the Ansible Plugin below is borrowed from the [jlafon/ansible-profile] project.
Briefly, it’s a simple plugin that keeps the run time of each playbook task in memory and displays those times before the playbook ends. The code should be self-explanatory, and the comments cover the parts of the plugin that need explaining.
| |
Below is sample output of the ‘profile_tasks’ Callback Plugin.
| |
PS. Since I wrote this, almost the same feature ships with Ansible as profile_tasks. (These days it lives in the ansible.posix collection.) Also, from Ansible 2.11 the callback_whitelist setting was renamed to callbacks_enabled, so keep that in mind on recent versions.