Ansible callback plugins enable adding new behaviors to Ansible when responding to events. By default, callback plugins control most of the output we see when running the command line programs, but can also be used to add additional output, integrate with other tools and marshal the events to a storage backend.

To use a callback plugin, we need to create a Python file in our Ansible project directory and define a class that inherits from one of Ansible’s built-in callback classes. We can then override any of the methods in the parent class to customize its behavior.
Here’s an example of how we can use a callback plugin to send notifications when a playbook run completes:
from ansible.plugins.callback import CallbackBase
import requests
class SlackNotificationCallback(CallbackBase):
def v2_playbook_on_stats(self, stats):
if stats.failures > 0:
message = f"Playbook failed on {stats.failures} hosts"
else:
message = "Playbook completed successfully"
requests.post(
"https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX",
json={"text": message},
)
This callback plugin sends a notification to a Slack channel when a playbook run completes.
We can find more information about Ansible callback plugins in the official documentation.
By default, Ansible ships with a number of callback plugins that control most of the output we see when running the command line programs.
Here are some of the most commonly used callback plugins:
- default: This is the default callback plugin that controls most of the output we see when running Ansible commands.
- json: This callback plugin outputs events in JSON format.
- minimal: This callback plugin provides minimal output.
- profile_tasks: This callback plugin outputs timing information for each task in a playbook.
We can change the callback plugin in the ansible.cfg configuration file in the [defaults] section with the stdout_callback option.
stdout_callback = dense
We can find more information about these and other built-in Ansible plugins in the official documentation.