In Lesson 10.1 you wrote a module, code that travels to the servers; in 10.2 you configured an inventory plugin, code that runs on your computer. That's Ansible's great divide: modules do the work on the managed hosts, and plugins extend the Ansible engine itself on the control node: how it connects, how it escalates privileges, how it transforms data in Jinja, where it reads information from, how it displays results and where it stores its cache. Almost everything you've used in the course is a plugin: ssh, sudo, default, password, jsonfile, free, timer… In this lesson you'll meet every type, see how Ansible finds them, and write four for the aurora_store.infra collection: the nginx_upstreams filter, which finally replaces the load balancer's dict(... | zip(...)) expression; the semver test, which validates the website version before deploying it; the catalog lookup, which queries the catalog API from your computer; and the summary callback, which displays a summary at the end of every run and can send it to the team's channel.
- Modules and plugins: where each one runs
| Module | Plugin | |
|---|---|---|
| Where it runs | On the managed host (or the delegate) | On the control node, inside the ansible-playbook process |
| How it's invoked | A task: aurora_store.infra.nginx_upstream_server: |
It depends on the type: | filter, is test, lookup(), configuration (callbacks_enabled), automatically (connection, become)… |
| Communication | JSON over standard output | Direct Python calls to engine classes and functions |
| Available libraries | Those of the server's Python | Those of Ansible's Python on your computer (or in the EE) |
| Base class | AnsibleModule |
One per type: LookupBase, CallbackBase, BaseInventoryPlugin… (filters and tests are functions) |
| Errors | fail_json |
Exceptions from ansible.errors (AnsibleFilterError, AnsibleLookupError…) |
Two practical consequences, which you already sensed back in Lesson 5.3 with lookups:
- A plugin sees all the variables and can read files, environment variables and network services on your computer, with your credentials. That's why a malicious plugin is so dangerous (Lesson 6.1), and why yours must be careful.
- A plugin that needs a library (for example,
boto3foraws_ec2) needs it on the control node and in the EE, not on the servers.
- The types of plugins
| Type | What it's for | Examples you've already used | How it's activated |
|---|---|---|---|
filter |
Transforming data in Jinja: {{ x | filter }} |
default, map, dict2items, to_nice_json, regex_escape |
By using it in an expression |
test |
Yes/no questions in Jinja: {{ x is test }} |
defined, changed, version, match |
By using it in an expression |
lookup |
Bringing data to the control node: lookup('x', ...) / query('x', ...) |
file, env, password, first_found, kubernetes.core.k8s |
By using it in an expression |
callback |
Reacting to run events (displaying, logging, notifying) | default (the output), ansible.posix.timer, profile_tasks |
stdout_callback (one) or callbacks_enabled (several) |
connection |
How to reach the host | ssh, local, community.docker.docker, kubernetes.core.kubectl |
ansible_connection / connection: |
inventory |
Building the inventory | yaml, ini, constructed, amazon.aws.aws_ec2 |
An inventory source (-i) |
become |
How to escalate privileges | sudo, su, community.general.doas |
become_method |
cache |
Where to store facts and the inventory cache | memory, jsonfile (Lesson 9.3) |
fact_caching, cache_plugin |
strategy |
How tasks are distributed across hosts | linear, free (Lesson 9.3), host_pinned, debug |
strategy: / [defaults] strategy |
vars |
Loading variables from other sources | host_group_vars (reads group_vars/ and host_vars/) |
Enabled by default / vars_plugins_enabled |
module_utils |
Not a plugin: code shared by modules (and reusable from plugins) | basic, urls, your nginx_upstream (Lesson 10.1) |
import |
There are more, less common types: action (code that runs on the control node before a module; template is an action plugin that renders on your computer and then calls copy), shell (sh, powershell), netconf/cliconf/httpapi (network devices), terminal, doc_fragments (reusable pieces of documentation). To list those of one type:
- How Ansible finds plugins
| Location | Example | When |
|---|---|---|
| Directory adjacent to the playbook | playbooks/filter_plugins/, playbooks/lookup_plugins/, playbooks/callback_plugins/ |
Quick tests or something for a single project |
| Inside a role | roles/<role>/filter_plugins/… |
Available once the role is loaded |
| Configuration | filter_plugins = ..., lookup_plugins = ... in ansible.cfg or ANSIBLE_FILTER_PLUGINS |
Common paths on a machine (discouraged: it depends on each computer) |
| Collection | plugins/filter/, plugins/test/, plugins/lookup/, plugins/callback/… |
Shared, versioned, with FQCN and documentation |
The rules for collections, which is where Aurora puts them (the decision from Lesson 10.1):
- The FQCN of a lookup or a callback is
aurora_store.infra.<file name>. - Filters and tests are different: a single file can contain several of them, and the name that counts is the one returned by the
filters()ortests()method. Theplugins/filter/nginx.pyfile can offeraurora_store.infra.nginx_upstreamsand, in the future, other nginx filters. - They're always used with FQCN. A filter from a collection can't be called by its short name (except with the
collections:keyword, which Aurora doesn't use, Lesson 2.6).
Create the directories in the collection:
cd ~/ansible_collections/aurora_store/infra
mkdir -p plugins/filter plugins/test plugins/lookup plugins/callback tests/unit/plugins/filterAnd turn the development loop from Lesson 10.1 back on in the terminal where you test from aurora-infra:
- A custom filter:
nginx_upstreams
nginx_upstreams4.1. The problem
Since Lesson 5.7 (and with aurora_internal_ip since 9.1), playbooks/group_vars/loadbalancers.yml has contained:
# Web servers the traffic is distributed to: {internal IP: weight}.
nginx_upstream_servers: >-
{{ dict(groups['webservers']
| map('extract', hostvars, 'aurora_internal_ip')
| zip(groups['webservers'] | map('extract', hostvars, 'aurora_lb_weight'))) }}It works, and in Lesson 5.3 you needed a diagram to explain it: two parallel lists (addresses and weights), zip to pair them up and dict to turn the pairs into a dictionary. Its problems: it's hard to read and modify, it goes through groups['webservers'] twice and, if a host is missing the variable, the Jinja error doesn't say which one.
We want to write:
nginx_upstream_servers: >-
{{ groups['webservers']
| aurora_store.infra.nginx_upstreams(hostvars, address='aurora_internal_ip', weight='aurora_lb_weight') }}4.2. The code
Create plugins/filter/nginx.py:
# -*- coding: utf-8 -*-
# Copyright: (c) 2026, Aurora Store
# MIT License (see LICENSE)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.errors import AnsibleFilterError
def nginx_upstreams(hosts, hostvars, address='ansible_host', weight=None, default_weight=1):
"""Build {address: weight} for the nginx role's upstream block."""
servers = {}
for host in hosts:
if host not in hostvars:
raise AnsibleFilterError('nginx_upstreams: host "%s" is not in the inventory.' % host)
host_vars = hostvars[host]
host_address = host_vars.get(address)
if not host_address:
raise AnsibleFilterError(
'nginx_upstreams: host "%s" does not have the variable "%s".' % (host, address)
)
host_weight = host_vars.get(weight, default_weight) if weight else default_weight
try:
host_weight = int(host_weight)
except (TypeError, ValueError):
raise AnsibleFilterError(
'nginx_upstreams: the weight of "%s" is not a number: %s' % (host, host_weight)
)
if host_weight < 1:
raise AnsibleFilterError(
'nginx_upstreams: the weight of "%s" must be 1 or more (it is %d).' % (host, host_weight)
)
servers[str(host_address)] = host_weight
return servers
class FilterModule(object):
"""nginx filters of the aurora_store.infra collection."""
def filters(self):
return {
'nginx_upstreams': nginx_upstreams,
}How a filter works, based on this example:
- A filter is a Python function. The value to the left of
|arrives as the first argument (hosts); the arguments in parentheses come next (hostvars, and by nameaddressandweight). Whatever the function returns is the result of the expression. - The
FilterModuleclass with thefilters()method is the "registry": Ansible looks for it in every file inplugins/filter/and callsfilters()to find out which names it offers and which function corresponds to each. hostvarsarrives as a special Ansible object, which behaves like a dictionary of hosts:hostvars[host]returns that host's variables and.get(name)returns a variable (already rendered:aurora_internal_ip: "{{ ansible_host }}"arrives as192.168.56.11) orNoneif it doesn't exist. That's why it has to be passed as an argument: a filter has no access to the play's variables except those it receives.- Default argument values (
address='ansible_host',default_weight=1) make the filter useful outside Aurora too:groups['webservers'] | aurora_store.infra.nginx_upstreams(hostvars)usesansible_hostand a weight of 1. host_vars.get(weight, default_weight) if weight else default_weightis a Python conditional expression: if the name of the weight variable was given, it looks it up (withdefault_weightif the host lacks it); if not, it usesdefault_weight.int(host_weight)converts the weight: in YAML it can arrive as a number or as a string ("2"). If it can't, you getValueErrorand a clear message.AnsibleFilterErroris the right exception: Ansible shows it as "The filter plugin '...' failed:", pointing to the task and the line. Compare that with the error from the original zipwhen a host is missingaurora_lb_weight.str(host_address)guarantees that the keys are strings.- The filter has no side effects: it doesn't read files or the network. That's what's expected of a filter: a pure transformation that can be evaluated many times (remember from Lesson 5.3 that variables are evaluated every time they're used).
- Documenting filters and tests: the adjacent YAML file
Modules carry their documentation in DOCUMENTATION inside the .py file. Filters and tests can't (one file contains several), so they're documented with a YAML file named after the filter, next to the code: plugins/filter/nginx_upstreams.yml.
DOCUMENTATION:
name: nginx_upstreams
version_added: "1.2.0"
short_description: Builds the list of servers for an nginx upstream
description:
- "Takes a list of inventory hosts and returns a C({address: weight}) dictionary
in the format of the nginx role's C(nginx_upstream_servers) variable."
positional: _input, hostvars
options:
_input:
description: Names of the inventory hosts (for example, C(groups['webservers'])).
type: list
elements: str
required: true
hostvars:
description: The C(hostvars) magic variable.
type: dict
required: true
address:
description: Variable of each host that contains its address.
type: str
default: ansible_host
weight:
description: Variable of each host that contains its weight. If omitted, they all weigh O(default_weight).
type: str
default_weight:
description: Weight of the hosts that don't define the O(weight) variable.
type: int
default: 1
author:
- Alex Admin (@alexadmin-aurora)
EXAMPLES: |
# {"192.168.56.11": 2, "192.168.56.12": 1}
nginx_upstream_servers: >-
{{ groups['webservers']
| aurora_store.infra.nginx_upstreams(hostvars, address='aurora_internal_ip', weight='aurora_lb_weight') }}
RETURN:
_value:
description: Dictionary with each host's address as the key and its weight as the value.
type: dict_inputis, by convention, the value to the left of|;positionalsays which arguments can be passed without a name, and in what order.RETURN._valuedescribes the filter's result.- The first description is in quotes because it contains
:insideC({address: weight})(the YAML warning from Lesson 10.1).
ansible-doc -t filter aurora_store.infra.nginx_upstreams
ansible-doc -t filter -l aurora_store.infra
- Using the filter in Aurora's load balancer
Before changing anything, test that the filter gives exactly the same result as the current expression:
ansible lb1 --playbook-dir playbooks -m ansible.builtin.debug -a "var=nginx_upstream_servers"
ansible lb1 --playbook-dir playbooks -m ansible.builtin.debug \
-a "msg={{ groups['webservers'] | aurora_store.infra.nginx_upstreams(hostvars, address='aurora_internal_ip', weight='aurora_lb_weight') }}"Both commands should show {"192.168.56.11": 2, "192.168.56.12": 1}. Now go ahead and change playbooks/group_vars/loadbalancers.yml:
# Web servers the traffic is distributed to: {internal IP: weight}.
# Filter from the aurora_store.infra collection (Lesson 10.3).
nginx_upstream_servers: >-
{{ groups['webservers']
| aurora_store.infra.nginx_upstreams(hostvars, address='aurora_internal_ip', weight='aurora_lb_weight') }}And the acid test of every refactoring in Aurora (Lesson 4.1): no change on the servers.
changed=0: the nginx role's site.conf.j2 template generates the same file. Trigger an error to see the difference in the messages: ansible lb1 --playbook-dir playbooks -m ansible.builtin.debug -a "var=nginx_upstream_servers" -e aurora_lb_weight=0 ends with "nginx_upstreams: the weight of "web1" must be 1 or more (it is 0)". (The -e variable beats everything, so it affects both web servers; the filter stops at the first one.)
In
stagingit works the same way:loadbalancersis empty and nobody evaluates the variable. Ifstagingever gets a load balancer, the filter will receive the private IPs thataws_ec2.ymlcomputes withcompose(Lesson 10.2).
- A Jinja2 test:
semver
semverThe website version (aurora_app_version) comes from three places: the inventory, the AWX survey (Lesson 7.3) and CI's web-X.Y.Z tag (Lesson 8.3), which validates it in shell. If someone deploys from AWX with 1.5 or v1.5.0, today it's discovered late: in the check in aurora_app's rescue block, after the web server has already been taken out of the load balancer. A custom test lets you validate it at the very start.
A test is like a filter that returns True or False and is used with is. Create plugins/test/versions.py:
# -*- coding: utf-8 -*-
# Copyright: (c) 2026, Aurora Store
# MIT License (see LICENSE)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import re
_SEMVER_RE = re.compile(r'^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$')
def semver(value):
"""True if value is an X.Y.Z version (no "v" prefix and no suffixes)."""
return isinstance(value, str) and _SEMVER_RE.match(value) is not None
class TestModule(object):
"""Version tests of the aurora_store.infra collection."""
def tests(self):
return {
'semver': semver,
}TestModulewith thetests()method is the equivalent ofFilterModule.- The regular expression requires three numbers separated by dots, with no leading zeros (
(0|[1-9][0-9]*): either a lone zero, or a number that doesn't start with zero), as SemVer requires (Lesson 6.4).^and$anchor to the start and the end: nothing else is allowed. isinstance(value, str)rules out numbers: if someone writesaurora_app_version: 1.5without quotes, YAML reads it as a decimal number (Lesson 3.2), and the test rejects it instead of converting it.
Its documentation, plugins/test/semver.yml:
DOCUMENTATION:
name: semver
version_added: "1.2.0"
short_description: Checks that a value is an X.Y.Z version
description:
- True if the value is a string in the C(MAJOR.MINOR.PATCH) format, with no C(v)
prefix, no suffixes and no leading zeros.
options:
_input:
description: Value being checked.
type: raw
required: true
author:
- Alex Admin (@alexadmin-aurora)
EXAMPLES: |
valid_version: "{{ aurora_app_version is aurora_store.infra.semver }}"
RETURN:
_value:
description: Whether the value is an X.Y.Z version.
type: boolTry it:
ansible localhost -m ansible.builtin.debug \
-a "msg={{ ['1.4.0', 'v1.4.0', '1.4', '1.04.0'] | select('aurora_store.infra.semver') | list }}"
ansible localhost -m ansible.builtin.debug -a "msg={{ '1.5' is aurora_store.infra.semver }}"Like any Jinja test, it can be used with is/is not and with the select and reject filters, which take the name of a test (map, on the other hand, takes the name of a filter). Adopt it in playbooks/webservers.yml, as the first task in pre_tasks (before taking the web server out of the load balancer):
- name: Check the format of the website version
ansible.builtin.assert:
that: aurora_app_version is aurora_store.infra.semver
fail_msg: "aurora_app_version must have the X.Y.Z format (it is '{{ aurora_app_version }}')"
quiet: true
tags: alwaysTest the failure without touching anything: ansible-playbook playbooks/webservers.yml --check -e aurora_app_version=v1.5.0 stops at this task, with both web servers still in the load balancer.
- A custom lookup:
catalog
catalogA lookup brings data to the control node: it reads a file, an environment variable, an API… The catalog API is a good candidate: from your computer it's reachable through the cluster's Ingress (http://catalog.aurora-store.example:30088, Lesson 8.2), and querying its /health or its product list is useful for checks and for debugging. (The API on api1, on the other hand, has only listened on 127.0.0.1 since Lesson 9.2: for that one, use the aurora_catalog_info module from Exercise 2 of Lesson 10.1, which runs on api1.)
Create plugins/lookup/catalog.py:
# -*- coding: utf-8 -*-
# Copyright: (c) 2026, Aurora Store
# MIT License (see LICENSE)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = r'''
name: catalog
author:
- Alex Admin (@alexadmin-aurora)
version_added: "1.2.0"
short_description: Queries the Aurora Store catalog API
description:
- Returns the catalog API's response for each requested resource, already
converted from JSON.
- Like all lookups, it runs on the control node.
options:
_terms:
description: Resources to query (C(health) or C(products)).
type: list
elements: str
required: true
url:
description: Base URL of the API.
type: str
default: http://localhost:8080
env:
- name: AURORA_CATALOG_URL
vars:
- name: aurora_catalog_url
timeout:
description: Maximum number of seconds to wait for each response.
type: int
default: 10
'''
EXAMPLES = r'''
- name: Show the version of the cluster's catalog API
ansible.builtin.debug:
msg: "{{ lookup('aurora_store.infra.catalog', 'health', url='http://catalog.aurora-store.example:30088').version }}"
- name: Count the published products
ansible.builtin.debug:
msg: "{{ query('aurora_store.infra.catalog', 'products')[0] | length }}"
'''
RETURN = r'''
_list:
description: One API response (dictionary or list) for each requested resource.
type: list
elements: raw
'''
import json
from ansible.errors import AnsibleLookupError
from ansible.module_utils.common.text.converters import to_native, to_text
from ansible.module_utils.urls import open_url
from ansible.plugins.lookup import LookupBase
ROUTES = {
'health': '/health',
'products': '/api/products',
}
class LookupModule(LookupBase):
def run(self, terms, variables=None, **kwargs):
self.set_options(var_options=variables, direct=kwargs)
base_url = self.get_option('url').rstrip('/')
timeout = self.get_option('timeout')
results = []
for term in terms:
if term not in ROUTES:
raise AnsibleLookupError(
'catalog: unknown resource "%s"; use one of: %s'
% (term, ', '.join(sorted(ROUTES)))
)
url = base_url + ROUTES[term]
self._display.vvv('catalog: querying %s' % url)
try:
response = open_url(url, timeout=timeout, headers={'Accept': 'application/json'})
results.append(json.loads(to_text(response.read())))
except ValueError as error:
raise AnsibleLookupError('catalog: %s did not return valid JSON: %s' % (url, to_native(error)))
except Exception as error:
raise AnsibleLookupError('catalog: could not query %s: %s' % (url, to_native(error)))
return resultsWhat's new compared to the filter:
- The documentation goes in
DOCUMENTATION, as in modules (one file = one lookup), but withname:instead ofmodule:. - Options are declared in the documentation and Ansible resolves them:
urlcan come from the named argument (url='...'), from the Ansible variableaurora_catalog_url(vars:), from the environment variableAURORA_CATALOG_URL(env:) or from the default value, with that precedence. You don't write any of that logic:self.set_options(var_options=variables, direct=kwargs)does it by reading yourDOCUMENTATION; afterwards,self.get_option('url')gives the final value. It's the same configuration system all the official plugins use. run(self, terms, variables=None, **kwargs)is the method Ansible calls.termsis the list of positional arguments ('health','products'),variablesthe available variables andkwargsthe named arguments.- It always returns a list, one element per term.
lookup()turns it into a single value (if there's only one element, that element);query()(orlookup(..., wantlist=True)) returns it as is (Lesson 5.3). open_url, fromansible.module_utils.urls, is Ansible's HTTP tool without a module: the same handling of certificates, proxies and timeouts asuriandfetch_url, with no external dependencies.self._display.vvv(...)writes a message only with-vvv. Neverprint().AnsibleLookupError, with messages that say which URL failed and why.
Try it against the cluster's API:
ansible localhost -m ansible.builtin.debug \
-a "msg={{ lookup('aurora_store.infra.catalog', 'health', url='http://catalog.aurora-store.example:30088') }}"
export AURORA_CATALOG_URL=http://catalog.aurora-store.example:30088
ansible localhost -m ansible.builtin.debug \
-a "msg={{ query('aurora_store.infra.catalog', 'products')[0] | map(attribute='name') | list }}"
unset AURORA_CATALOG_URLThe first shows {"status": "ok", "version": "1.0.0", "redis": true}; the second, the names of the three coffees in the inventory (Lesson 8.2): the catalog the role publishes, read back through the API. Also try a nonexistent resource ('prices') and a URL with no service behind it to see the error messages.
Why not a lookup that writes to the API? Because of the same rule from Lesson 10.1, and one more: lookups are evaluated every time the variable is used, sometimes more than once per task, and also under
--check. A lookup must read, never modify.
- A notification callback:
summary
summary9.1. What a callback is
While a playbook runs, Ansible generates events: the playbook starts, a play starts, a task starts, a task finishes fine on one host, fails on another, a host is unreachable, everything ends with the statistics. A callback is a class that listens to those events. The output you see in your terminal is the default callback; the total time Aurora has shown since Lesson 5.8 is ansible.posix.timer; AWX and ansible-runner (Lesson 10.4) use their own callback to store every event.
There are three types, according to CALLBACK_TYPE:
| Type | How many at once | What for | Example |
|---|---|---|---|
stdout |
One (stdout_callback) |
Drawing the output on screen | default, ansible.builtin.minimal, community.general.yaml (old) |
notification |
Several (callbacks_enabled) |
Notifying other systems | Email, chat, logging systems |
aggregate |
Several (callbacks_enabled) |
Accumulating and summarizing | ansible.posix.timer, profile_tasks |
9.2. The v2_* methods
A callback implements the methods for the events it cares about; it inherits the rest, empty, from CallbackBase. The most commonly used:
| Method | When it's called | Useful arguments |
|---|---|---|
v2_playbook_on_start(playbook) |
When the playbook starts | playbook._file_name |
v2_playbook_on_play_start(play) |
When each play starts | play.get_name() |
v2_playbook_on_task_start(task, is_conditional) |
When each task starts | task.get_name() |
v2_runner_on_ok(result) |
A task finishes fine on a host | result._host.get_name(), result._task.get_name(), result._result (the module's JSON) |
v2_runner_on_failed(result, ignore_errors=False) |
A task fails on a host | The same; ignore_errors tells you whether the failure is ignored |
v2_runner_on_skipped(result) |
A task is skipped | |
v2_runner_on_unreachable(result) |
A host doesn't respond | |
v2_runner_item_on_ok/failed/skipped(result) |
Each iteration of a loop | |
v2_playbook_on_handler_task_start(task) |
A handler starts | |
v2_playbook_on_stats(stats) |
At the end, with the PLAY RECAP statistics |
stats.processed, stats.summarize(host) |
9.3. The code
The goal: at the end of each run, a summary line (which playbook, whether it went well, how long it took, which hosts changed and which failed) and, if a webhook is configured, sending it to the Operations team's channel (Mattermost, Slack and similar tools accept a JSON document with a text key). Create plugins/callback/summary.py:
# -*- coding: utf-8 -*-
# Copyright: (c) 2026, Aurora Store
# MIT License (see LICENSE)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = r'''
name: summary
type: notification
author:
- Alex Admin (@alexadmin-aurora)
version_added: "1.2.0"
short_description: Summarizes each run and, optionally, sends it to a webhook
description:
- When the playbook finishes, it displays a summary line with the duration, the hosts
with changes and the hosts with failures.
- If O(webhook_url) is set, it sends that summary in a JSON document with a C(text) key, the format
accepted by the incoming webhooks of Mattermost, Slack and similar tools.
- A failure to send the notification never makes the playbook fail.
requirements:
- Enable it in C(callbacks_enabled) in C(ansible.cfg).
options:
webhook_url:
description: URL of the webhook the summary is sent to. Without it, the summary is only displayed.
type: str
env:
- name: AURORA_SUMMARY_WEBHOOK
ini:
- section: callback_summary
key: webhook_url
failures_only:
description: Send to the webhook only the runs with failures or unreachable hosts.
type: bool
default: false
env:
- name: AURORA_SUMMARY_FAILURES_ONLY
ini:
- section: callback_summary
key: failures_only
'''
import json
import time
from ansible.module_utils.common.text.converters import to_native
from ansible.module_utils.urls import open_url
from ansible.plugins.callback import CallbackBase
class CallbackModule(CallbackBase):
CALLBACK_VERSION = 2.0
CALLBACK_TYPE = 'notification'
CALLBACK_NAME = 'aurora_store.infra.summary'
CALLBACK_NEEDS_ENABLED = True
def __init__(self):
super(CallbackModule, self).__init__()
self.start = None
self.playbook = None
self.failures = []
def v2_playbook_on_start(self, playbook):
self.start = time.time()
self.playbook = playbook._file_name
def v2_runner_on_failed(self, result, ignore_errors=False):
if not ignore_errors:
self.failures.append('%s: %s' % (result._host.get_name(), result._task.get_name()))
def v2_runner_on_unreachable(self, result):
self.failures.append('%s: unreachable' % result._host.get_name())
def v2_playbook_on_stats(self, stats):
duration = int(time.time() - self.start) if self.start else 0
hosts = sorted(stats.processed.keys())
with_changes = []
with_failures = []
for host in hosts:
summary = stats.summarize(host)
if summary['changed']:
with_changes.append(host)
if summary['failures'] or summary['unreachable']:
with_failures.append(host)
status = 'FAILED' if with_failures else 'SUCCEEDED'
text = '[aurora-infra] %s: %s in %d s. Hosts: %d. With changes: %s. With failures: %s.' % (
self.playbook, status, duration, len(hosts),
', '.join(with_changes) or 'none', ', '.join(with_failures) or 'none',
)
if self.failures:
text += '\nFirst failures:\n- ' + '\n- '.join(self.failures[:5])
self._display.banner('AURORA STORE SUMMARY')
self._display.display(text)
url = self.get_option('webhook_url')
if url and (with_failures or not self.get_option('failures_only')):
self._send(url, text)
def _send(self, url, text):
try:
open_url(
url,
method='POST',
data=json.dumps({'text': text}),
headers={'Content-Type': 'application/json'},
timeout=10,
)
except Exception as error:
self._display.warning('summary: could not send the notification: %s' % to_native(error))Explanation:
- The class attributes identify the callback: the callback API version (
2.0), the type, the full name andCALLBACK_NEEDS_ENABLED = True, which means "don't load me unless I'm enabled incallbacks_enabled". Without that line, a callback from an installed collection could become active in every project. __init__sets up the state: a callback lives for the entire run and accumulates information across events.super(...).__init__()callsCallbackBase's initialization (essential).v2_playbook_on_startstores the start time and the playbook's file name.v2_runner_on_failedrecords each real failure: if the task hasignore_errors, it doesn't count. That way the summary shows which task failed on which host.v2_playbook_on_statsdoes the final work.stats.processedcontains the hosts that took part andstats.summarize(host)returns their counters (ok,changed,failures,unreachable,skipped,rescued,ignored): they're the numbers in thePLAY RECAP. A host whose tasks were rescued byrescuedoesn't count as failed (Lesson 5.5).self._display.banner(...)anddisplay(...)write to the screen in Ansible's style (the title with asterisks).- The options are declared in
DOCUMENTATIONas in the lookup, withenv:(environment variable) andini:(a dedicated section inansible.cfg). In callbacks, Ansible callsset_options()for you when loading them: all you have to do is useself.get_option(...).type: boolmakesAURORA_SUMMARY_FAILURES_ONLY=truearrive as a boolean. _sendmakes aPOSTwithopen_urland, if it fails, only issues a warning. It's the golden rule of a notification callback: it must never make a run fail because it couldn't send a notification.
9.4. Enabling and testing it
In aurora-infra's configuration (ansible.cfg, [defaults] section):
Run any playbook:
PLAY RECAP ********************************************************************* api1 : ok=... changed=0 ... ... AURORA STORE SUMMARY *********************************************************** [aurora-infra] common.yml: SUCCEEDED in 23 s. Hosts: 5. With changes: none. With failures: none. Playbook run took 0 days, 0 hours, 0 minutes, 23 seconds
To test the webhook without a real chat, start a single-request test receiver in another terminal (save it as /tmp/receiver.py; it just prints what it receives):
from http.server import BaseHTTPRequestHandler, HTTPServer
class Receiver(BaseHTTPRequestHandler):
def do_POST(self):
length = int(self.headers['Content-Length'])
print('RECEIVED:', self.rfile.read(length).decode(), flush=True)
self.send_response(200)
self.end_headers()
HTTPServer(('127.0.0.1', 18081), Receiver).handle_request()And in your working terminal, trigger a failure (web2 shut down, as in Lesson 1.5):
(cd lab && vagrant halt web2)
AURORA_SUMMARY_WEBHOOK=http://127.0.0.1:18081/hooks/test ansible-playbook playbooks/common.yml --check
(cd lab && vagrant up web2)The receiver prints something like:
RECEIVED: {"text": "[aurora-infra] common.yml: FAILED in 31 s. Hosts: 5. With changes: none. With failures: web2.\nFirst failures:\n- web2: unreachable"}And if the receiver is no longer listening, the playbook finishes all the same, with a warning: [WARNING]: summary: could not send the notification: ... Connection refused.
A webhook URL is a secret: whoever has it can post to the channel. Don't put it in
ansible.cfg(it's in the repository). Use the environment variable: on your computer, from your secrets manager; in AWX, as an environment variable injected by a custom credential type (like theAurora - Store APIexample from Lesson 7.5). That's why theini:option exists but Aurora doesn't use it.
Two notes on coexistence:
- Profiling from Lesson 5.8:
ANSIBLE_CALLBACKS_ENABLED=...replaces the list inansible.cfg. If you want the summary while profiling, include it:ANSIBLE_CALLBACKS_ENABLED=ansible.posix.timer,ansible.posix.profile_tasks,aurora_store.infra.summary. - AWX uses the project's
ansible.cfg, so the callback will be loaded there too (the collection is installed by the project sync). Without the environment variable, it just adds its line at the end of the job output; AWX already has its own notifications (Lesson 7.3), so the webhook makes more sense for runs from the terminal and from CI.
- Testing the plugins
Filters and tests are pure functions: they're tested with pytest, like the module_utils in Lesson 10.1. Create tests/unit/plugins/filter/test_nginx.py:
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import pytest
from ansible.errors import AnsibleFilterError
from ansible_collections.aurora_store.infra.plugins.filter.nginx import nginx_upstreams
HOSTVARS = {
'web1': {'aurora_internal_ip': '10.0.0.1', 'aurora_lb_weight': 2},
'web2': {'aurora_internal_ip': '10.0.0.2'},
}
def test_weights_and_default_weight():
result = nginx_upstreams(['web1', 'web2'], HOSTVARS,
address='aurora_internal_ip', weight='aurora_lb_weight')
assert result == {'10.0.0.1': 2, '10.0.0.2': 1}
def test_no_weight_variable():
assert nginx_upstreams(['web1'], HOSTVARS, address='aurora_internal_ip') == {'10.0.0.1': 1}
def test_host_without_address():
with pytest.raises(AnsibleFilterError, match='does not have the variable'):
nginx_upstreams(['web1'], HOSTVARS, address='ansible_host')
def test_invalid_weight():
hostvars = {'web1': {'ansible_host': '10.0.0.1', 'weight': 0}}
with pytest.raises(AnsibleFilterError, match='1 or more'):
nginx_upstreams(['web1'], hostvars, weight='weight')A plain dictionary stands in for hostvars: the filter only uses in, [] and .get(), which both offer. Since it imports ansible.errors, run it with the Python from aurora-infra's .venv, which has ansible-core:
cd ~/ansible_collections/aurora_store/infra
PYTHONPATH=$HOME ~/aurora-infra/.venv/bin/python -m pytest -q tests/unitThe eight from Lesson 10.1, the one from that lesson's Exercise 1 and these four. The lookup and the callback depend on the network and on the Ansible engine: they're better tested with integration tests (a target that uses the lookup against a test server) or, as you've done, by hand with a receiver. And before publishing, ansible-test sanity --docker default -v: it also checks the plugins' documentation (including the adjacent YAML files).
- Releasing version 1.2.0 and adopting it in
aurora-infra
aurora-infra11.1. In the collection
Four new plugins: a minor version, 1.2.0 (hence their version_added). If you did Exercise 2 of Lesson 10.1 and want to publish aurora_catalog_info, include it too: its version_added already said 1.2.0.
galaxy.yml:version: 1.2.0.CHANGELOG.md:
## 1.2.0 - 2026-11-26
### Added
- `aurora_store.infra.nginx_upstreams` filter: builds `{address: weight}` for the nginx role.
- `aurora_store.infra.semver` test: validates X.Y.Z versions.
- `aurora_store.infra.catalog` lookup: queries the catalog API (health and products).
- `aurora_store.infra.summary` callback: a summary of every run and an optional webhook notification.README.md: extend the contents table with the four plugins.
cd ~/ansible_collections/aurora_store/infra
git add galaxy.yml CHANGELOG.md README.md plugins tests
ansible-test sanity --docker default -v
git commit -m "nginx_upstreams filter, semver test, catalog lookup and summary callback (1.2.0)"
git tag -a 1.2.0 -m "Version 1.2.0"
git push origin main --tags11.2. In aurora-infra
On a branch (collection-plugins), stop using the development copy and pin the new version:
collections/requirements.yml: the collection's entry becomesversion: "1.2.0". Install withansible-galaxy collection install -r collections/requirements.yml(a collection with a different version is replaced without--force, Lesson 6.2).playbooks/group_vars/loadbalancers.yml:nginx_upstream_serverswith the filter (section 6).playbooks/webservers.yml: the "Check the format of the website version" task (section 7).ansible.cfg:callbacks_enabled = ansible.posix.timer, aurora_store.infra.summary(section 9.4).ee/execution-environment.yml: tagaurora-ee:1.4.0(the rule from Lesson 8.3 again:collections/requirements.ymlhas changed);ansible-navigator.yml: image1.4.0. Once merged and built, switch the organization's EE in AWX.CHANGELOG.md, under[Unreleased]: the filter in the load balancer, the version validation, the summary callback andaurora-ee:1.4.0.
Check before you commit:
changed=0, with the summary line at the end. Commit ("aurora_store.infra 1.2.0 plugins: load balancer filter, version validation and run summary; aurora-ee 1.4.0"), push, pull request and merge with CI green.
Common Mistakes and Tips
No filter named 'aurora_store.infra.nginx_upstreams': the collection isn't visible (checkANSIBLE_COLLECTIONS_PATHor the installed version) orfilters()doesn't return that name. Remember that for filters, the name in the dictionary is what counts, not the file name.- The filter can't see the hosts' variables: a filter only receives what you pass it. That's why
hostvarsis an argument. - Generic Python errors in a plugin (
KeyError,TypeError): they reach the user as cryptic messages. Catch the foreseeable cases and raise the appropriate Ansible exception with a message that says which host, which variable and which value. - A lookup that modifies something: it will be evaluated several times, and under
--checktoo. Lookups only read. - Forgetting
CALLBACK_NEEDS_ENABLED = Truein a notification callback: it would become active in any project that installs the collection. - A callback that raises exceptions: Ansible shows warnings on every event and the output becomes unreadable. Protect everything that depends on the network or on external data with
try/except. - Setting
ANSIBLE_CALLBACKS_ENABLEDand losing the summary: the variable replaces the list inansible.cfg; it doesn't extend it. - Writing the webhook URL into the repository: it's a secret. Use an environment variable or a credential.
- Tip: before writing a plugin, look in
community.general(ansible-doc -t filter -l community.general): it has dozens of filters and lookups, and what you need may already exist.
Exercises
Exercise 1: a second filter in the same file
Add to plugins/filter/nginx.py a filter aurora_store.infra.nginx_upstream_lines that takes the {address: weight} dictionary and a port, and returns the list of lines server <address>:<port> weight=<weight>;. Document it and test it with ansible localhost -m ansible.builtin.debug.
Exercise 2: a test for private addresses
Write a test aurora_store.infra.private_ip (in plugins/test/network.py) that returns true if an IPv4 address belongs to a private range (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16), using Python's standard ipaddress module. Where could Aurora use it?
Exercise 3: a callback that counts changes per task
Extend the summary callback (on a branch of the collection, without publishing it) so that it also lists the three tasks that changed the most hosts. Hint: v2_runner_on_ok(self, result) and result._result.get('changed').
Solutions
Exercise 1. In nginx.py:
def nginx_upstream_lines(servers, port=80):
"""Convert {address: weight} into nginx 'server' lines."""
return ['server %s:%s weight=%s;' % (address, port, weight)
for address, weight in servers.items()]And in filters(), 'nginx_upstream_lines': nginx_upstream_lines,. The expression in square brackets is a list comprehension: it builds the list by applying the text template to each (address, weight) pair in the dictionary. Its YAML file, plugins/filter/nginx_upstream_lines.yml, follows the model from section 5 (_input of type dict, port of type int with default: 80, _value of type list). Test:
ansible localhost -m ansible.builtin.debug \
-a "msg={{ {'10.0.0.1': 2} | aurora_store.infra.nginx_upstream_lines(80) }}"
# "msg": ["server 10.0.0.1:80 weight=2;"]Exercise 2. plugins/test/network.py:
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import ipaddress
def private_ip(value):
"""True if value is an IPv4 address in a private range (RFC 1918)."""
try:
address = ipaddress.IPv4Address(str(value))
except ValueError:
return False
return any(address in ipaddress.IPv4Network(network)
for network in ('10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16'))
class TestModule(object):
def tests(self):
return {'private_ip': private_ip}ipaddress.IPv4Address raises ValueError if the text isn't an IPv4 address, and the in operator checks membership of a network. (The standard library also offers the is_private property, but it includes other reserved ranges; here we want exactly RFC 1918.) Use in Aurora: an assert in staging-provision.yml or in the playbooks guaranteeing that aurora_internal_ip is private (if compose picked the wrong field and used the public IP, traffic between servers would go out to the Internet and the pg_hba.conf rules wouldn't match).
Exercise 3. Inside the class:
def v2_runner_on_ok(self, result):
if result._result.get('changed'):
task = result._task.get_name()
self.changes_per_task[task] = self.changes_per_task.get(task, 0) + 1with self.changes_per_task = {} in __init__, and in v2_playbook_on_stats:
top = sorted(self.changes_per_task.items(), key=lambda pair: pair[1], reverse=True)[:3]
if top:
text += '\nTasks with the most changes: ' + ', '.join('%s (%d)' % pair for pair in top)sorted(..., key=lambda pair: pair[1], reverse=True) sorts the (task, count) pairs by the count, from highest to lowest, and [:3] keeps the first three. Careful: with loops, v2_runner_on_ok receives the task's aggregated result (with changed true if any iteration changed); to count iterations, you'd implement v2_runner_item_on_ok.
Conclusion
Plugins extend the Ansible engine on the control node, and almost everything you do with Ansible goes through one: connection, become, inventory, variables, strategy, cache, output and, in every Jinja expression, filters, tests and lookups. You've seen that they're loaded from adjacent directories, from the configuration or, better, from a collection with FQCN; that filters and tests are functions registered by FilterModule and TestModule and documented with an adjacent YAML file; that lookups and callbacks are classes that declare their options in DOCUMENTATION and read them with get_option; and that a callback listens to the run's v2_* events. aurora_store.infra 1.2.0 contributes the filter that finally makes the load balancer readable, the test that validates the version before touching anything, the lookup that queries the catalog API and the callback that summarizes every run. So far, you've launched everything with ansible-playbook from a terminal, from CI or from AWX. But what if a program of your own needs to launch a playbook and react to what happens in each task, the way AWX does internally? In the next lesson, The Ansible API and ansible-runner, you'll see why it's not a good idea to use Ansible's internal classes from Python, and how ansible-runner and the AWX REST API offer a stable interface for integrating Ansible into your own tools.
