For nine modules you've automated Aurora Store using only what ships with ansible-core and the community collections: apt, template, uri, docker_compose_v2, k8s… That's almost always the right call. But somewhere in every real project there's a task that no module handles well and that ends up being written with command, shell or a fragile regular expression. In Aurora that corner has existed since Lesson 5.7: the two ansible.builtin.replace tasks in playbooks/webservers.yml that take each web server out of the load balancer and put it back with a regular expression nobody wants to touch. In this lesson you'll learn how to decide when it's worth writing your own module, how to build one in Python with AnsibleModule (documentation, argument validation, check mode, diffs, errors and results), how to share code with module_utils, how to test it with ansible localhost -m, ansible-doc, pytest and ansible-test, and how to publish it in the aurora_store.infra collection so that aurora-infra can replace those two tasks with a clear, idempotent, tested module.
- When to write a module (and when not to)
A custom module is code you'll have to maintain, test and document for years. Before writing one, go through the alternatives in this order:
| Option | When it's enough | Limitation |
|---|---|---|
| An existing module (core or collection) | Almost always: search with ansible-doc -l and on Galaxy first |
— |
| Combining modules in a role | The task is a sequence of known steps (install, configure, start) | It's what Aurora's roles already do |
ansible.builtin.template / copy |
Ansible is the sole owner of the entire file | Doesn't work if others modify parts of the file |
lineinfile / replace / blockinfile |
Small, stable changes in files owned by others | Fragile regular expressions; replace doesn't warn you if it finds nothing |
ansible.builtin.uri |
Simple calls to a REST API | Idempotency (query → compare → modify) has to be written by hand across several tasks |
command / shell + changed_when |
A command-line tool with no equivalent | Hard to make idempotent, no real --check, no --diff |
| Custom module | Repeated logic, with state to compare, that needs reliable idempotency, --check and --diff |
It has to be maintained and tested |
Signs that a custom module is justified:
- The same combination of tasks (query, compare, decide, modify) shows up in several places.
- A regular expression or a
jqfilter that only its author understands. - You need
--check --diffto tell the truth (AWX's nightly check, Lesson 7.3, depends on it). - You have to talk to an API or a format for which there's no module, and the "is it already the way I want?" logic is non-trivial.
And signs that it isn't:
- There's a module that does 90% of the job and the gap can be closed with a parameter or an extra task.
- What you want is to reuse tasks: that's a role (Module 4).
- What you want is to transform data inside Jinja: that's a filter (Lesson 10.3).
- What you want is to read data on the control node: that's a lookup (Lesson 10.3).
What about a module to manage products through the catalog API? It's the idea that comes to mind when you think about "talking to the store's internal API". But the catalog API from Module 8 is read-only by design: it reads
products.json, which theaurora_catalogrole publishes fromaurora_catalog_productsin the inventory. A module that created products through the API would give the catalog two owners (the inventory and the module), exactly what the "one owner per resource" rule from Lesson 8.5 forbids. For querying the API you will have your own tools: theaurora_store.infra.cataloglookup in Lesson 10.3 and an_infomodule in Exercise 2 of this lesson.
- The Aurora case: taking a web server out of the load balancer
This is what the tasks that take each web server out of the load balancer before deploying it look like today (after Lesson 9.1) in playbooks/webservers.yml:
- name: Take the server out of the load balancer
ansible.builtin.replace:
path: /etc/nginx/sites-available/aurora
regexp: '^(\s*server {{ hostvars[inventory_hostname]["aurora_internal_ip"] | regex_escape }}:\d+ weight=\d+);$'
replace: '\1 down;'
delegate_to: "{{ item }}"
loop: "{{ groups['loadbalancers'] }}"
changed_when: false
tags: alwaysAnd its counterpart in post_tasks, "Put the server back into the load balancer", with another expression that removes the down. They work, but they have real problems:
| Problem | Consequence |
|---|---|
The expression requires exactly IP:port weight=N; |
If one day the nginx role adds max_fails=3 to the line, the expression stops matching |
replace doesn't fail if it finds nothing |
The web server doesn't leave the load balancer, nobody notices and customers see errors during the deployment |
You have to escape the IP with regex_escape and understand capture groups |
Nobody on the team wants to touch them; a typo goes unnoticed |
| Two different expressions for going in and out | Duplicated logic that can drift apart |
What we need is an operation with a meaning of its own: "in upstream block X of this file, set server Y to down (or up)", which fails with a clear message if it can't find the block or the server, touches nothing else, is idempotent and works with --check and --diff. That's a module: aurora_store.infra.nginx_upstream_server. It's generic (it serves any project that uses the nginx role, such as blog-infra), so its natural home is the aurora_store.infra collection.
- How Ansible runs a module: the contract
Remember Lesson 1.4: Ansible packages the module (AnsiballZ format), copies it to the host, runs it with Python and reads the response. The exchange is always JSON:
sequenceDiagram
participant C as Control node
participant H as Managed host (lb1)
C->>C: Renders the task arguments (Jinja)
C->>H: Copies AnsiballZ_nginx_upstream_server.py (module + module_utils + arguments)
H->>H: python3 runs the module
Note over H: AnsibleModule validates the arguments,<br/>the module does its work
H-->>C: JSON on standard output: {"changed": true, "line": "...", ...}
C->>H: Deletes the temporary files
C->>C: Interprets changed/failed, shows the diff, saves the register
The contract has few rules, but they're strict:
| Rule | Detail |
|---|---|
| Input | The arguments arrive as JSON; AnsibleModule reads and validates them for you |
| Output | A single JSON document on standard output. No stray print() calls: they would break the JSON |
| Success | module.exit_json(changed=..., ...) |
| Failure | module.fail_json(msg="...", ...): msg is mandatory |
| Special keys | changed, failed, msg, diff, warnings, deprecations, invocation… |
| Where it runs | On the managed host (or the delegate): it can only use the Python and libraries of that host |
The last row is the big difference from plugins (Lesson 10.3), which run on the control node. That's why a module should depend as little as possible on external libraries: lb1 has Ubuntu's Python and not much else.
A module can be written in any language that reads an arguments file and writes JSON (there are binary modules, and Windows modules are PowerShell), but on Linux the standard is Python with AnsibleModule, which gives you validation, check mode, type conversion, atomic file writes and much more. That's what you'll use.
- Where a module lives
Ansible looks for modules in several places. Choose based on who's going to use it:
| Location | Who sees it | When to use it |
|---|---|---|
library/ next to the playbook (in Aurora, playbooks/library/) |
The playbooks in that directory | Quick tests, single-project modules |
roles/<role>/library/ |
The role's tasks (and the play that uses it, once loaded) | A module that only makes sense inside a role |
library = ... in ansible.cfg or ANSIBLE_LIBRARY |
Everything using that configuration | Not recommended: you depend on each machine's configuration |
plugins/modules/ in a collection |
Any project that installs the collection, with FQCN | Shared, versioned, documented and tested modules |
An example of the first option, so you can see how easy it is to get started: if you save a file playbooks/library/hello.py, a task can use it as hello: (no FQCN; internally it's ansible.legacy.hello). It's handy for experimenting, but it clashes with several Aurora conventions: it has no FQCN (ansible-lint with the production profile flags it), it isn't versioned separately and it can't be shared with blog-infra.
- The collection as the home for modules and plugins
In Lesson 6.5 you created aurora_store.infra in ~/ansible_collections/aurora_store/infra, with the common, nginx and postgresql roles and the upgrade playbook, and you left the plugins/ folder ready. You also made a decision: aurora-infra does not consume the collection; the collection is the distribution package for other teams and is regenerated from aurora-infra and ansible-role-nginx.
Modules and plugins change that situation, so it's worth settling the decision for the rest of the course:
- The collection's Python code (
plugins/) is written directly in the collection's repository: its source of truth isansible-collection-infra. There's nowhere else to regenerate it from. - The collection's roles stay as in Lesson 6.5: they're regenerated from
aurora-infra(common,postgresql) andansible-role-nginx(nginx). aurora-infrastarts consuming the collection (from Gitea, with a pinned version) only for its modules and plugins. It keeps taking its roles fromroles/andgalaxy_roles/, as before; that way there aren't two copies ofcommoncompeting.
The structure of the collection at the end of this module will be:
~/ansible_collections/aurora_store/infra/
├── galaxy.yml, README.md, LICENSE, CHANGELOG.md, meta/runtime.yml
├── playbooks/upgrade.yml
├── roles/{common, nginx, postgresql}/
├── plugins/
│ ├── modules/nginx_upstream_server.py (this lesson)
│ ├── module_utils/nginx_upstream.py (this lesson)
│ ├── filter/, test/, lookup/, callback/ (Lesson 10.3)
└── tests/
└── unit/plugins/module_utils/test_nginx_upstream.py (this lesson)Create the directories:
cd ~/ansible_collections/aurora_store/infra
git status # clean tree before starting
mkdir -p plugins/modules plugins/module_utils tests/unit/plugins/module_utilsRemember the naming rule for collections: the file name (without .py) is the module name, and its FQCN is aurora_store.infra.<name>. Use lowercase and underscores.
module_utils: the logic, separate and reusable
module_utils: the logic, separate and reusableBefore the module, write the logic: given the text of an nginx file, mark a server in an upstream as down or up. You put it in plugins/module_utils/ for three reasons:
- It can be tested without Ansible: they're pure Python functions that take text and return text; the unit tests need neither servers nor
AnsibleModule. - It can be reused: another module (for example, one that lists the state of every server in an
upstream) would import the same functions. - It travels with the module: when Ansible packages a module, it automatically includes the
module_utilsit imports. You don't have to install anything onlb1.
Create plugins/module_utils/nginx_upstream.py:
# -*- coding: utf-8 -*-
# Copyright: (c) 2026, Aurora Store
# MIT License (see LICENSE)
"""Functions for reading and modifying nginx upstream blocks."""
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import re
_UPSTREAM_RE = re.compile(r'^\s*upstream\s+(?P<name>[^\s{]+)\s*\{')
_SERVER_RE = re.compile(
r'^(?P<indent>\s*)server\s+(?P<address>[^\s;]+)(?P<params>[^;]*);(?P<rest>.*)$'
)
class UpstreamError(Exception):
"""Error when looking for the upstream or the server in the configuration."""
def split_address(address):
"""Split 'host:port' into (host, port). The port may be None."""
if address.startswith('['):
# IPv6: [2001:db8::1]:80
host, sep, rest = address[1:].partition(']')
port = rest[1:] if rest.startswith(':') else None
return host, port
if address.count(':') == 1:
host, port = address.split(':')
return host, port
return address, None
def set_server_state(text, upstream, server, port=None, down=True):
"""Mark a server in an upstream as out of service (down=True) or active.
Return a tuple (new_text, final_line, previous_state).
Raise UpstreamError if the upstream or the server is not found.
"""
lines = text.splitlines(True)
in_upstream = False
upstream_found = False
result_line = None
previous = None
for index, line in enumerate(lines):
if not in_upstream:
match = _UPSTREAM_RE.match(line)
if match and match.group('name') == upstream:
in_upstream = True
upstream_found = True
continue
if line.strip().startswith('}'):
in_upstream = False
continue
content = line.rstrip('\r\n')
newline = line[len(content):]
match = _SERVER_RE.match(content)
if not match:
continue
host, server_port = split_address(match.group('address'))
if host != server or (port is not None and server_port != str(port)):
continue
params = match.group('params').split()
previous = 'down' if 'down' in params else 'up'
if down and 'down' not in params:
params.append('down')
elif not down:
params = [param for param in params if param != 'down']
new_content = '%sserver %s%s;%s' % (
match.group('indent'),
match.group('address'),
''.join(' ' + param for param in params),
match.group('rest'),
)
lines[index] = new_content + newline
result_line = new_content.strip()
if not upstream_found:
raise UpstreamError('Cannot find the upstream block "%s".' % upstream)
if result_line is None:
raise UpstreamError(
'Server "%s" does not appear in the upstream block "%s".' % (server, upstream)
)
return ''.join(lines), result_line, previousExplanation, block by block, for those who don't program in Python every day:
- Header:
# -*- coding: utf-8 -*-declares the encoding (so messages can safely contain non-ASCII characters); the copyright and license lines are a collection convention. The string between triple quotes is the file's documentation (docstring). from __future__ ...and__metaclass__ = type: lines inherited from the days when modules also had to work on Python 2. On Python 3 they change nothing, but many collections keep them and someansible-testchecks expect them in code that declares older compatibility. Copying them is harmless.import re: the regular expression module from the standard library. We only use the standard library: nothing to install on the servers._UPSTREAM_RE: recognizes a line likeupstream aurora_backend {and captures the name in thenamegroup.\s*= optional whitespace;[^\s{]+= one or more characters that are neither whitespace nor{. The leading underscore in the variable name means "internal use"._SERVER_RE: recognizesserver 192.168.56.11:80 weight=2;and splits it into four named pieces:indent(the indentation, so we can preserve it),address(192.168.56.11:80),params(weight=2, everything up to the;) andrest(whatever follows the;, for example a comment). It no longer matters which parameters the line has: we treat them as a list.class UpstreamError(Exception): a custom error type. The module will catch it and turn it into afail_jsonwith a clear message.split_address: splits"192.168.56.11:80"into("192.168.56.11", "80"). It handles addresses without a port (web1→("web1", None)) and IPv6 addresses in square brackets.partition(']')splits the text into three parts: what comes before the first], the]itself and what comes after.set_server_state, the heart of it:text.splitlines(True)splits the file into lines keeping the line breaks (True), so it can be rebuilt identically at the end.- It goes through the lines with
enumerate, which gives both the position (index) and the content (line). - While it is not inside the requested
upstream, it only checks whether the line opens that block. When it finds it, it setsin_upstream. - Inside the block, a line starting with
}closes it. - For each
serverline, it compares the address (and the port, if one was requested). If it's not the one we're looking for,continuemoves on to the next one. paramsis the list of parameters (['weight=2']). It saves the previous state, and adds or removesdownonly if needed: that's idempotency. If the server is already as requested, the rebuilt line is identical to the original.- It rebuilds the line preserving the indentation and whatever came after the
;, and stores it in the list. - At the end, if it didn't find the block or the server, it raises an error: the opposite of
replace, which kept quiet. - It returns the full text, the resulting line and the previous state.
Notice what it does not do: it doesn't read or write files and knows nothing about Ansible. It takes text and returns text. That's what makes it easy to test.
- Anatomy of a module:
nginx_upstream_server line by line
nginx_upstream_server line by lineCreate plugins/modules/nginx_upstream_server.py. You'll see it in full first and then piece by piece:
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2026, Aurora Store
# MIT License (see LICENSE)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = r'''
---
module: nginx_upstream_server
short_description: Enables or takes out of service a server in an nginx upstream
version_added: "1.1.0"
description:
- Looks for a server inside an C(upstream) block of an nginx configuration
file and adds or removes the C(down) parameter.
- It only modifies that line; the rest of the file is left untouched.
- It does not reload nginx. Do that in a later task or with a handler.
options:
path:
description: Path of the configuration file that contains the C(upstream) block.
type: path
required: true
upstream:
description: Name of the C(upstream) block.
type: str
required: true
server:
description: Address of the server (IP or name), without the port.
type: str
required: true
port:
description:
- Port of the server.
- If omitted, every line with that address is modified, whatever its port.
type: int
state:
description:
- V(up) removes the C(down) parameter; V(down) adds it.
type: str
choices: [up, down]
default: up
backup:
description: Saves a copy of the file before modifying it.
type: bool
default: false
notes:
- Supports check mode (C(--check)) and diff mode (C(--diff)).
author:
- Alex Admin (@alexadmin-aurora)
'''
EXAMPLES = r'''
- name: Take web1 out of the load balancer
aurora_store.infra.nginx_upstream_server:
path: /etc/nginx/sites-available/aurora
upstream: aurora_backend
server: 192.168.56.11
state: down
- name: Put it back, only on port 80
aurora_store.infra.nginx_upstream_server:
path: /etc/nginx/sites-available/aurora
upstream: aurora_backend
server: 192.168.56.11
port: 80
state: up
'''
RETURN = r'''
line:
description: The server line as it ends up in the file.
returned: success
type: str
sample: "server 192.168.56.11:80 weight=2 down;"
previous_state:
description: State of the server before the module ran.
returned: success
type: str
sample: up
backup_file:
description: Path of the backup copy.
returned: changed and backup is true
type: str
sample: /etc/nginx/sites-available/aurora.12345.2026-11-26@10:00:00~
'''
import os
import tempfile
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text
from ansible_collections.aurora_store.infra.plugins.module_utils.nginx_upstream import (
UpstreamError,
set_server_state,
)
def main():
argument_spec = dict(
path=dict(type='path', required=True),
upstream=dict(type='str', required=True),
server=dict(type='str', required=True),
port=dict(type='int'),
state=dict(type='str', default='up', choices=['up', 'down']),
backup=dict(type='bool', default=False),
)
module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
path = module.params['path']
if not os.path.isfile(path):
module.fail_json(msg='File %s does not exist.' % path, path=path)
with open(path, 'rb') as config_file:
before = to_text(config_file.read(), errors='surrogate_or_strict')
try:
after, line, previous = set_server_state(
before,
upstream=module.params['upstream'],
server=module.params['server'],
port=module.params['port'],
down=module.params['state'] == 'down',
)
except UpstreamError as error:
module.fail_json(msg=to_native(error), path=path)
result = dict(
changed=after != before,
path=path,
line=line,
previous_state=previous,
)
if module._diff:
result['diff'] = dict(
before=before,
after=after,
before_header=path,
after_header=path,
)
if result['changed'] and not module.check_mode:
if module.params['backup']:
result['backup_file'] = module.backup_local(path)
fd, tmp_path = tempfile.mkstemp(dir=module.tmpdir)
with os.fdopen(fd, 'wb') as tmp_file:
tmp_file.write(to_bytes(after, errors='surrogate_or_strict'))
module.atomic_move(tmp_path, path)
module.exit_json(**result)
if __name__ == '__main__':
main()7.1. The header
#!/usr/bin/python: the shebang. Ansible replaces it with the host's actual interpreter (ansible_python_interpreter, which in Aurora is discovered byinterpreter_python = auto_silent). For modules it must be exactly this line:ansible-test sanitychecks it.- The rest of the header is the same as in
module_utils.
7.2. The documentation: DOCUMENTATION, EXAMPLES and RETURN
They're three strings with YAML inside, and they aren't decorative:
| Variable | What it's for | Who reads it |
|---|---|---|
DOCUMENTATION |
Name, description, options (type, required, default value, allowed values), author, version it was added in | ansible-doc, Galaxy, ansible-test sanity (checks that it matches the code) |
EXAMPLES |
Example tasks ready to copy | ansible-doc, people |
RETURN |
Which keys the module returns, when, and of what type | ansible-doc, whoever uses register |
Details worth knowing:
- The
rin front of'''makes the string raw: Python doesn't interpret backslashes. Always use it. version_addedis the version of the collection in which the module appears ("1.1.0", quoted so it isn't read as a number).- Formatting markup:
C(text)= code,V(value)= a value of an option,O(option)= an option,I(text)= italics.ansible-docconverts them when displaying. authorin theName (@user)format:ansible-testrequires it.- Inside a YAML list, watch out for
:: a description like- Returns C({ip: weight})breaks because YAML sees a key. Quote it. - Option names are in English by ecosystem convention (
path,state,server); in an internal collection, the help texts could be written in your team's own language. - The
importstatements go after the documentation, by convention: that wayansible-doccan read the documentation without running the code.
7.3. The import statements
AnsibleModule: the class that does almost all the heavy lifting.to_bytes,to_text,to_native: safe converters between bytes and text. Files are read as bytes ('rb') and converted to text withto_text; for writing, the other way around.errors='surrogate_or_strict'prevents an odd character from making the module fail uncontrollably.to_nativeconverts an error into a string for the message.from ansible_collections.aurora_store.infra.plugins.module_utils.nginx_upstream import ...: the way to import a collection'smodule_utils, always with the full pathansible_collections.<namespace>.<collection>.plugins.module_utils.<file>. Ansible detects this line and putsnginx_upstream.pyinside the AnsiballZ package.
7.4. argument_spec: declaring the arguments
argument_spec is a dictionary with one entry per option. AnsibleModule uses it to validate and convert the arguments before your code sees them: if someone writes state: offline, it fails with a clear message without you having written a single line of validation.
| Key | Meaning | Example |
|---|---|---|
type |
Type the value is converted to | str, int, bool, float, list, dict, path, raw, bytes, jsonarg |
required |
Mandatory | required=True |
default |
Value if none is given | default='up' |
choices |
Allowed values | choices=['up', 'down'] |
aliases |
Other accepted names | aliases=['dest'] |
elements |
Type of each element of a list |
type='list', elements='str' |
no_log |
Never show the value (secrets) | no_log=True |
options |
Suboptions of a dict or of a list of dict |
(as in the roles' argument_specs.yml, Lesson 4.6) |
And in the AnsibleModule constructor, rules between options: mutually_exclusive, required_together, required_one_of, required_if (for example, required_if=[('state', 'present', ['url'])]).
The path type deserves a mention: as well as being text, it expands ~ and environment variables. Notice too that argument_spec and DOCUMENTATION say the same thing with different syntax; ansible-test sanity will check that they match (if they don't, you get a doc-default-does-not-match-spec error or similar).
Remember the roles'
meta/argument_specs.yml(Lesson 4.6): it's the same idea, applied to a role's variables instead of a module's arguments.
7.5. AnsibleModule(...) and supports_check_mode
- It reads the arguments, validates them and leaves the result in the
module.paramsdictionary. supports_check_mode=Truepromises that the module honors--check. If it wereFalse, in check mode Ansible wouldn't even run it and would show the task asskipped. Making the promise means keeping it: in check mode, compute what would change, but don't change it. You'll check this withmodule.check_mode.
7.6. The module's work
- Check that the file exists: if not,
fail_json. Every error should end in afail_jsonwith amsgexplaining what's wrong; an uncaught Python error also makes the task fail, but with a scary traceback that doesn't help. - Read the current state (
before). - Compute the desired state (
after) with themodule_utilsfunction, turningUpstreamErrorintofail_json. - Compare:
changedis simplyafter != before. This is the recipe for idempotency: read, compute, compare, and only write if there's a difference.
7.7. Diff mode
if module._diff:
result['diff'] = dict(before=before, after=after, before_header=path, after_header=path)module._diff is true when running with --diff (or diff: true on the task). If the result has a diff key with before and after, Ansible shows the difference line by line, just like with template. It's what makes AWX's nightly check useful: it doesn't just say "would change", but what.
7.8. Writing the file safely
if result['changed'] and not module.check_mode:
if module.params['backup']:
result['backup_file'] = module.backup_local(path)
fd, tmp_path = tempfile.mkstemp(dir=module.tmpdir)
with os.fdopen(fd, 'wb') as tmp_file:
tmp_file.write(to_bytes(after, errors='surrogate_or_strict'))
module.atomic_move(tmp_path, path)- It only writes if there are changes and we're not in check mode.
backup_localcopies the file with a timestamp in its name (likebackup: trueintemplate, Lesson 5.2) and returns the path.- Atomic write: the full content is written to a temporary file (in
module.tmpdir, the module's temporary directory) andatomic_moverenames it over the original. A rename is atomic: nginx (or whoever reads the file) sees either the old content or the new one, never a half-written file. In addition,atomic_movepreserves the owner, permissions and SELinux context of the original file.
7.9. The result
exit_json turns the dictionary into the output JSON and ends the program. The ** "unpacks" the dictionary as named arguments. We return changed (mandatory in practice), the resulting line and the previous state: useful data for a register. Since the result includes the path key, AnsibleModule automatically adds file information (owner, permissions, size), just as file or copy do.
Finally, if __name__ == '__main__': main() is the Python idiom for "run main() when this file is launched as a program".
- Testing the module by hand
8.1. Making the collection visible during development
While you're developing, Ansible has to find the collection in ~/ansible_collections. It's the development loop from Lesson 6.5, extended: from ~/aurora-infra, the environment variable overrides collections_path in ansible.cfg, so include collections/ as well to keep seeing community.general and friends:
cd ~/aurora-infra
export ANSIBLE_COLLECTIONS_PATH="$HOME:$PWD/collections"
ansible-doc aurora_store.infra.nginx_upstream_serveransible-doc should show the description, the options (with the required ones highlighted), the examples and the return values. If it shows a documentation error, it's almost always malformed YAML inside DOCUMENTATION: the message gives the line and column within the string.
8.2. Ad hoc against localhost
Create a test file with the same format that the nginx role's site.conf.j2 template generates:
cat > /tmp/test-upstream.conf <<'EOF'
upstream aurora_backend {
server 192.168.56.11:80 weight=2;
server 192.168.56.12:80 weight=1;
}
EOFFirst, in check mode and with diffs:
ansible localhost -m aurora_store.infra.nginx_upstream_server \
-a "path=/tmp/test-upstream.conf upstream=aurora_backend server=192.168.56.11 state=down" \
--check --diff--- before: /tmp/test-upstream.conf
+++ after: /tmp/test-upstream.conf
@@ -1,4 +1,4 @@
upstream aurora_backend {
- server 192.168.56.11:80 weight=2;
+ server 192.168.56.11:80 weight=2 down;
server 192.168.56.12:80 weight=1;
}
localhost | CHANGED => {
"changed": true,
"line": "server 192.168.56.11:80 weight=2 down;",
"path": "/tmp/test-upstream.conf",
"previous_state": "up",
...
}cat /tmp/test-upstream.conf confirms that it has not changed (it was --check). Now for real, with a backup, and then repeat it to check idempotency:
ansible localhost -m aurora_store.infra.nginx_upstream_server \
-a "path=/tmp/test-upstream.conf upstream=aurora_backend server=192.168.56.11 state=down backup=true"
ansible localhost -m aurora_store.infra.nginx_upstream_server \
-a "path=/tmp/test-upstream.conf upstream=aurora_backend server=192.168.56.11 state=down"The first returns CHANGED with backup_file; the second, SUCCESS with "changed": false and "previous_state": "down". Finally, trigger the errors that replace kept quiet about:
ansible localhost -m aurora_store.infra.nginx_upstream_server \
-a "path=/tmp/test-upstream.conf upstream=aurora_backen server=192.168.56.11"
ansible localhost -m aurora_store.infra.nginx_upstream_server \
-a "path=/tmp/test-upstream.conf upstream=aurora_backend server=192.168.56.99"
ansible localhost -m aurora_store.infra.nginx_upstream_server \
-a "path=/tmp/test-upstream.conf upstream=aurora_backend server=192.168.56.11 state=offline"localhost | FAILED! => { "msg": "Cannot find the upstream block \"aurora_backen\".", ... }
localhost | FAILED! => { "msg": "Server \"192.168.56.99\" does not appear in the upstream block \"aurora_backend\".", ... }
localhost | FAILED! => { "msg": "value of state must be one of: up, down, got: offline" }You didn't program the third error: AnsibleModule generates it from choices.
8.3. Running the module without Ansible (debugging)
When something fails in a strange way, it helps to run the module directly with Python. AnsibleModule accepts a JSON file with the arguments as its first parameter:
cat > /tmp/args.json <<'EOF'
{"ANSIBLE_MODULE_ARGS": {"path": "/tmp/test-upstream.conf", "upstream": "aurora_backend",
"server": "192.168.56.11", "state": "up"}}
EOF
PYTHONPATH=$HOME python3 -m ansible_collections.aurora_store.infra.plugins.modules.nginx_upstream_server /tmp/args.jsonPYTHONPATH=$HOMElets Python find theansible_collectionspackage in~/ansible_collections.- The output is the raw JSON. Here you can temporarily add a
print()or use a debugger; under Ansible, thatprint()would break the JSON.
Another useful tool: ANSIBLE_KEEP_REMOTE_FILES=1 keeps the AnsiballZ_*.py file that Ansible copies to the host (with -vvv you'll see its path). Running it with python3 AnsiballZ_nginx_upstream_server.py explode extracts the package contents so you can inspect them.
- Unit tests with
pytest
pytestManual tests are useful while you write; automated tests are what protect the module when someone changes it six months from now. Since the logic lives in module_utils, it's tested with plain pytest functions.
Create tests/unit/plugins/module_utils/test_nginx_upstream.py:
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import pytest
from ansible_collections.aurora_store.infra.plugins.module_utils.nginx_upstream import (
UpstreamError,
set_server_state,
split_address,
)
CONFIG = """upstream aurora_backend {
server 192.168.56.11:80 weight=2;
server 192.168.56.12:80 weight=1;
}
server {
listen 80 default_server;
location / {
proxy_pass http://aurora_backend;
}
}
"""
def test_mark_down():
new, line, previous = set_server_state(CONFIG, 'aurora_backend', '192.168.56.11', down=True)
assert line == 'server 192.168.56.11:80 weight=2 down;'
assert previous == 'up'
assert 'server 192.168.56.12:80 weight=1;' in new
def test_back_to_up():
with_down, dummy, dummy2 = set_server_state(CONFIG, 'aurora_backend', '192.168.56.11', down=True)
new, line, previous = set_server_state(with_down, 'aurora_backend', '192.168.56.11', down=False)
assert previous == 'down'
assert new == CONFIG
def test_idempotent():
first, dummy, dummy2 = set_server_state(CONFIG, 'aurora_backend', '192.168.56.11', down=True)
second, dummy, previous = set_server_state(first, 'aurora_backend', '192.168.56.11', down=True)
assert first == second
assert previous == 'down'
def test_different_port_does_not_match():
with pytest.raises(UpstreamError):
set_server_state(CONFIG, 'aurora_backend', '192.168.56.11', port=8080)
def test_nonexistent_upstream():
with pytest.raises(UpstreamError, match='upstream'):
set_server_state(CONFIG, 'other_backend', '192.168.56.11')
@pytest.mark.parametrize('address, expected', [
('192.168.56.11:80', ('192.168.56.11', '80')),
('web1', ('web1', None)),
('[2001:db8::1]:80', ('2001:db8::1', '80')),
])
def test_split_address(address, expected):
assert split_address(address) == expectedHow to read it:
pytestruns every function whose name starts withtest_. Eachassertis a check: if the expression is false, the test fails andpytestshows the values.CONFIGis a sample nginx file, with an extraserverblock to check that it isn't touched.test_back_to_upchecks the round trip: afterdownandup, the text is identical to the original (not a single extra space).test_idempotentapplies the same thing twice and requires the same result: the most important property of an Ansible module, turned into a test.pytest.raises(UpstreamError)checks that an error is raised;match=also requires the message to contain a given text.@pytest.mark.parametrizeruns the same test with several sets of input data.dummyis a conventional name for values that aren't used (theansible-teststyle checks accept it without warnings).
Run them with the aurora-infra .venv (Lesson 9.4), where you add pytest:
~/aurora-infra/.venv/bin/pip install pytest
cd ~/ansible_collections/aurora_store/infra
PYTHONPATH=$HOME ~/aurora-infra/.venv/bin/python -m pytest -q tests/unitEight tests: five functions plus three split_address cases. Now the acid test: break the logic (for example, change if down and 'down' not in params to if down) and run them again: test_idempotent fails and tells you why. Undo the change.
What about testing the whole module, with
AnsibleModule? It can be done, by simulating the arguments and capturingexit_json/fail_json, but the internals of that simulation have changed betweenansible-coreversions. For a module whose logic lives inmodule_utils, the recommended combination is: unit tests for the logic + integration tests for the whole module (a small playbook intests/integration/targets/nginx_upstream_server/tasks/main.ymlthat creates a file, runs the module and checks withassert;ansible-test integrationruns it). You'll write one in Exercise 3.
ansible-test sanity and ansible-test units
ansible-test sanity and ansible-test unitsIn Lesson 9.5 you met ansible-test in passing. Now the collection has Python code and it really comes into its own. ansible-test ships with ansible-core and must be run inside .../ansible_collections/aurora_store/infra. In addition, it only examines files known to Git, so commit (or at least git add) first:
cd ~/ansible_collections/aurora_store/infra
git add plugins tests
ansible-test sanity --docker default -v--docker defaultruns the tests in the official test container, which has every Python version the collection must support and the tools (pylint,pycodestyle…) at the right versions. It also works with Podman. The first time, it downloads the image.- The alternative without containers:
ansible-test sanity --venv --python 3.12, faster but less thorough.
Some of the most important sanity tests:
| Test | What it checks |
|---|---|
validate-modules |
That DOCUMENTATION is valid YAML, matches argument_spec (types, defaults, choices), has an author with (@user), version_added, etc. |
compile |
That the code compiles on all the Python versions supported by the managed hosts (not just yours) |
import |
That modules only import what will be available on the host |
pylint, pep8 |
Likely bugs and style |
shebang |
#!/usr/bin/python in modules |
yamllint |
The YAML in the documentation and in the collection's files |
A typical error the first time:
ERROR: plugins/modules/nginx_upstream_server.py:0:0: doc-default-does-not-match-spec:
Argument 'state' in argument_spec defines default as ('up') but documentation defines default as ('down')You fix the code or the documentation, never ignore it. Only if an exception is justified (for example, a file generated by another tool) do you record it in tests/sanity/ignore-2.17.txt (one line per file and test); ansible-lint's sanity rule checks that those exceptions are among the permitted ones.
The unit tests, with the same tool:
It runs the same pytest tests as before, but on every supported Python version and in the environment the collection expects. It's the "official" way; plain pytest is your fast loop while developing.
About versions.
ansible-core2.17 has already reached the end of its support (Lesson 9.4), and eachansible-coreversion'sansible-testknows its own Python versions and rules. When Aurora upgradesansible-core(a pending task for the final project), expect some newsanityrule; that's why the exceptions file has the version in its name.
- Module best practices
| Practice | Why | In nginx_upstream_server |
|---|---|---|
| Idempotency: read, compare and only change if needed | It's Ansible's basic promise; without it, changed means nothing |
changed = after != before |
| Real check mode | AWX's nightly check and people's --check depend on it |
supports_check_mode=True + not module.check_mode before writing |
Diffs with --diff |
Knowing what would change, not just that it changes | diff key with before/after |
Errors with fail_json and clear messages |
The message is the only thing the user will see | "Server X does not appear in the upstream block Y" |
| Print nothing | The output must be a single JSON document | No print() |
| Complete, consistent documentation | ansible-doc is the help; ansible-test verifies it |
DOCUMENTATION, EXAMPLES, RETURN |
| Minimal dependencies on the host | The module runs on the managed server | Standard library only |
| Atomic writes | Never leave a half-written file | tempfile + atomic_move |
| Return useful data | For register, assert and debugging |
line, previous_state, backup_file |
| One module, one responsibility | Easy to understand and test | It doesn't reload nginx: that's another task |
Three more practices this module doesn't need, but yours might:
Secrets: no_log. If a module receives a password or a token, declare the option with no_log=True. AnsibleModule will hide it in the output, in -vvv and in the result (invocation), replacing it with VALUE_SPECIFIED_IN_NO_LOG_PARAMETER:
argument_spec = dict(
api_url=dict(type='str', required=True),
api_token=dict(type='str', required=True, no_log=True),
)In addition, AnsibleModule warns you if an option has a name that looks like a secret (password, token, secret…) and doesn't have no_log. Don't silence that warning: declare it. It's the module-level equivalent of no_log: true on tasks from Lesson 5.4.
Optional dependencies: missing_required_lib. If you need a library that might not be on the host, import it inside a try and, if it's missing, fail with a standard message:
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# ... inside main(), after creating the module:
if not HAS_REQUESTS:
module.fail_json(msg=missing_required_lib('requests'))That way the error says "requests is missing on the host" instead of a cryptic ImportError (it's what you saw in Lesson 8.1 with community.docker).
HTTP APIs: fetch_url and open_url. To talk to an API from a module, don't use requests (it isn't on every host): use fetch_url from ansible.module_utils.urls, which honors the standard options (validate_certs, proxies, timeout) and returns the response and an info dictionary with the status code. Its cousin open_url is the version without a module, the one the plugins in Lesson 10.3 will use. You'll practice it in Exercise 2.
And a naming convention: modules that only query end in _info (docker_container_info, k8s_info), never return changed: true and always support --check.
- Releasing version 1.1.0 of the collection
12.1. Version, changelog and documentation
A new module is new, backward-compatible functionality: according to SemVer (Lesson 6.4), a minor version. In galaxy.yml:
In CHANGELOG.md, above the 1.0.0 entry:
## 1.1.0 - 2026-11-26
### Added
- `aurora_store.infra.nginx_upstream_server` module: enables or takes out of service
a server in an nginx `upstream` block, with `--check` and `--diff`.
- `nginx_upstream` `module_utils` and its unit tests.And in the contents table of the collection's README.md, a new row for the module. Check that the collection builds (Lesson 6.5):
ansible-galaxy collection build --output-path ~/aurora-dist
# Created collection for aurora_store.infra at ~/aurora-dist/aurora_store-infra-1.1.0.tar.gz12.2. Commit, tag and Gitea
git add galaxy.yml CHANGELOG.md README.md plugins tests
git commit -m "nginx_upstream_server module with module_utils and unit tests (1.1.0)"
git tag -a 1.1.0 -m "Version 1.1.0"In Module 7 the collection stayed, at most, in an optional private Gitea repository. Now aurora-infra is going to depend on it, and it will be installed by your team, CI, AWX's project sync and the EE build. Apply the same solution you chose for ansible-role-nginx in Lesson 7.4 (option A): a public repository within the internal network, readable without credentials.
- In Gitea (as
alex), in theopsorganization: ifansible-collection-infradoesn't exist, create it empty; if it exists and is private, switch it to public under Settings. - Point the remote at it and push the branch and the tags:
git remote set-url origin http://git.aurora-store.example/ops/ansible-collection-infra.git \
|| git remote add origin http://git.aurora-store.example/ops/ansible-collection-infra.git
git push -u origin main --tagsThe || runs the second command only if the first one fails (that is, if there was no origin remote yet). The bare repository ~/aurora-git/ansible-collection-infra.git from Module 6 is no longer used, like the rest of ~/aurora-git/.
- Using the module in
aurora-infra
aurora-infraWork on a branch, as always since Lesson 9.4:
cd ~/aurora-infra
git switch -c balancer-module
unset ANSIBLE_COLLECTIONS_PATH # from here on, the installed collection13.1. Declaring the dependency
In collections/requirements.yml, at the end:
# Aurora Store's own collection (Lesson 10.1). Its modules and plugins are used;
# its roles are NOT (Aurora's roles stay in roles/ and galaxy_roles/).
- name: git+http://git.aurora-store.example/ops/ansible-collection-infra.git
type: git
version: "1.1.0"type: git+version:ansible-galaxyclones the repository at the1.1.0tag, builds the collection and installs it incollections/ansible_collections/aurora_store/infra.- Its dependencies (
community.general>=12.0.0,<13.0.0andcommunity.postgresql>=4.0.0,<5.0.0, Lesson 6.5) are compatible with the versions Aurora already pins (12.6.7 and 4.2.2): nothing else is installed.
ansible-galaxy collection install -r collections/requirements.yml
ansible-galaxy collection list aurora_store.infra
ansible-doc aurora_store.infra.nginx_upstream_server | head -513.2. Replacing the two tasks in webservers.yml
In playbooks/webservers.yml, pre_tasks:
- name: Take the server out of the load balancer
aurora_store.infra.nginx_upstream_server:
path: /etc/nginx/sites-available/aurora
upstream: aurora_backend
server: "{{ hostvars[inventory_hostname]['aurora_internal_ip'] }}"
state: down
delegate_to: "{{ item }}"
loop: "{{ groups['loadbalancers'] }}"
changed_when: false
tags: alwaysAnd in post_tasks:
- name: Put the server back into the load balancer
aurora_store.infra.nginx_upstream_server:
path: /etc/nginx/sites-available/aurora
upstream: aurora_backend
server: "{{ hostvars[inventory_hostname]['aurora_internal_ip'] }}"
state: up
delegate_to: "{{ item }}"
loop: "{{ groups['loadbalancers'] }}"
changed_when: false
tags: alwaysWhat changes and what doesn't:
- The two regular expressions disappear: the task says what it wants (
state: down), not how to edit the text. aurora_backendis the name generated by thenginxrole'ssite.conf.j2template ({{ nginx_site_name }}_backend, withnginx_site_name: aurora), as is the file path.delegate_to, the loop overgroups['loadbalancers'](empty instaging: the loop does nothing), the reload tasks and thealwaystag stay.changed_when: falsestays, for the same reason as in Lesson 5.7: taking the web server out and putting it back is a deployment operation, not a configuration change, and it mustn't spoil thechanged=0of repeated runs or of the nightly check.- It gains a new behavior: if the web server's IP isn't in the load balancer (inconsistent inventory, changed template), the task fails before deploying, and
max_fail_percentage: 0stops the deployment. Before, the deployment carried on with the web server still in the load balancer.
13.3. Testing it
ansible-lint playbooks/webservers.yml
ansible-playbook playbooks/webservers.yml --check --diff
ansible-playbook playbooks/webservers.ymlWith the curl loop against http://192.168.56.10/ from Lesson 5.7 running in another terminal, the store should respond throughout the deployment, alternating between web1 and web2 except while one of them is out. The final result is changed=0 if there was nothing to deploy.
13.4. The execution environment, CI and AWX
You've changed collections/requirements.yml, so the pipeline rule from Lesson 8.3 kicks in: the ee.yml workflow will rebuild aurora-ee and will fail if the tag already exists. The latest one is 1.2.0 (Lesson 8.4), so in the same change bump the version and deal with a new detail: until now, all the collections came from Galaxy, and this one comes from Git. ansible-builder installs the collections in an intermediate build stage that starts from the base image, where git isn't installed (the git-core from dependencies.system only reaches the final image). In ee/execution-environment.yml:
additional_build_steps:
# The aurora_store.infra collection is installed from Git: the stage that runs
# ansible-galaxy needs the git client.
prepend_galaxy:
- RUN /usr/bin/dnf install -y git-core
options:
package_manager_path: /usr/bin/dnf
tags:
- registry.aurora-store.example:5000/aurora/aurora-ee:1.3.0And in ansible-navigator.yml, image: registry.aurora-store.example:5000/aurora/aurora-ee:1.3.0.
Everything else works unchanged:
| Where | What happens |
|---|---|
CI (lint, syntax, tests) |
They install collections/requirements.yml; the runner on awx1 reads the public Gitea repository |
| AWX, project sync | It installs the project's collections (Lesson 7.4), including aurora_store.infra |
| AWX, organization EE | Once merged and the image is built, switch the organization's EE to aurora-ee 1.3.0 (as in Lessons 7.6 and 8.3) |
Record the change in aurora-infra's CHANGELOG.md ([Unreleased] section):
### Changed
- `webservers.yml` takes the web servers out of the load balancer and puts them back with the
`aurora_store.infra.nginx_upstream_server` module (collection 1.1.0) instead of `replace`.
- Execution environment `aurora-ee:1.3.0` (own collection from Git).Commit, push the branch, open the pull request and merge once CI is green:
git add collections/requirements.yml playbooks/webservers.yml ee/execution-environment.yml \
ansible-navigator.yml CHANGELOG.md
git commit -m "Load balancer: nginx_upstream_server module from aurora_store.infra 1.1.0; aurora-ee 1.3.0"
git push -u origin balancer-moduleCommon Mistakes and Tips
couldn't resolve module/action 'aurora_store.infra.nginx_upstream_server': Ansible can't find the collection. During development, checkANSIBLE_COLLECTIONS_PATH(it must contain the parent directory ofansible_collections, that is,$HOME); inaurora-infra, check that you've runansible-galaxy collection install -r collections/requirements.yml.- Leaving
ANSIBLE_COLLECTIONS_PATHexported: if you leave it in your~/.bashrc, you'll use the development copy without realizing it instead of the pinned version. Export it only in your development terminal. MODULE FAILUREwith a Python traceback: an uncaught exception. Read the last line of the traceback, reproduce it with the arguments file (section 8.3) and turn it into afail_jsonwith a clear message.- A forgotten debugging
print(): Ansible showsMODULE FAILUREand "Module invocation had junk after the JSON data", or it can't read the JSON. Remove it. supports_check_mode=Truewithout checkingmodule.check_mode: the module would modify servers under--check. It's the worst possible mistake in a module: it destroys trust in check mode altogether.- Documentation and
argument_specout of sync:ansible-docwould say one thing and the module would do another.ansible-test sanitycatches it: run it before every release. DOCUMENTATIONYAML broken by a:inside a text: quote that line of the description.- Using control node libraries in a module: the module runs on the managed host. If it works against
localhostand fails onlb1, suspect an import. - Changing a module's behavior without changing the collection version: once a tag is published, it's immutable (Lesson 6.5). Every change gets a new version and a
CHANGELOG.mdentry. - Tip: write the test for the case you want to handle first (for example, "it also works with
max_fails=3on the line") and then the code. With the logic inmodule_utils, it's very cheap.
Exercises
Exercise 1: extra parameters on the line
The team wants the nginx role to add max_fails=3 fail_timeout=10s to every server in the upstream. Without touching the module's code, write a new unit test proving that set_server_state still works with a line like server 10.40.1.15:80 weight=1 max_fails=3 fail_timeout=10s; and that down is added at the end. Run it with pytest. Would the old regular expressions in webservers.yml have worked?
Exercise 2: an _info module for the catalog API
Write plugins/modules/aurora_catalog_info.py, a read-only module that queries the catalog API from api1 itself (where it listens on 127.0.0.1:8080, Lesson 9.2) with fetch_url and returns its status (/health) and the number of products (/api/products). Options: url (default http://127.0.0.1:8080) and timeout (default 10). It must fail with a clear message if the API doesn't respond or returns a code other than 200. Test it with ansible api1 --playbook-dir playbooks -m aurora_store.infra.aurora_catalog_info.
Exercise 3: an integration test
Create the integration target tests/integration/targets/nginx_upstream_server/tasks/main.yml that: creates a temporary configuration file on the test host, takes a server out (and checks changed), repeats it (and checks that nothing changes), puts it back and verifies that the file has ended up the same as at the start. Run it with ansible-test integration --docker default nginx_upstream_server.
Solutions
Exercise 1. Add to test_nginx_upstream.py:
def test_line_with_more_parameters():
config = "upstream aurora_backend {\n server 10.40.1.15:80 weight=1 max_fails=3 fail_timeout=10s;\n}\n"
new, line, previous = set_server_state(config, 'aurora_backend', '10.40.1.15', down=True)
assert line == 'server 10.40.1.15:80 weight=1 max_fails=3 fail_timeout=10s down;'
back, dummy, dummy2 = set_server_state(new, 'aurora_backend', '10.40.1.15', down=False)
assert back == configpytest passes: the module treats the parameters as a list, so it doesn't care how many there are. The old expressions required the line to end exactly in weight=\d+;: with max_fails they wouldn't have matched, replace would have done nothing without failing, and the web server would have been deployed without leaving the load balancer. It's the best justification for the module.
Exercise 2. One solution:
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2026, Aurora Store
# MIT License (see LICENSE)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = r'''
---
module: aurora_catalog_info
short_description: Queries the status and products of the Aurora Store catalog API
version_added: "1.2.0"
description:
- Calls C(/health) and C(/api/products) on the catalog API. It changes nothing.
options:
url:
description: Base URL of the API, as seen from the host where the module runs.
type: str
default: http://127.0.0.1:8080
timeout:
description: Maximum number of seconds to wait for each response.
type: int
default: 10
author:
- Alex Admin (@alexadmin-aurora)
'''
EXAMPLES = r'''
- name: Query the catalog API
aurora_store.infra.aurora_catalog_info:
register: aurora_catalog_info
'''
RETURN = r'''
health:
description: Response from C(/health).
returned: success
type: dict
sample: {"status": "ok", "version": "1.0.0", "redis": true}
products:
description: Number of published products.
returned: success
type: int
sample: 3
'''
import json
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.urls import fetch_url
def query(module, path):
url = module.params['url'].rstrip('/') + path
response, info = fetch_url(module, url, timeout=module.params['timeout'])
if info['status'] != 200:
module.fail_json(msg='%s returned %s: %s' % (url, info['status'], info.get('msg')))
try:
return json.loads(response.read())
except ValueError:
module.fail_json(msg='%s did not return valid JSON.' % url)
def main():
module = AnsibleModule(
argument_spec=dict(
url=dict(type='str', default='http://127.0.0.1:8080'),
timeout=dict(type='int', default=10),
),
supports_check_mode=True,
)
health = query(module, '/health')
products = query(module, '/api/products')
module.exit_json(changed=False, health=health, products=len(products))
if __name__ == '__main__':
main()fetch_url(module, url, ...)returns the response (orNone) andinfo, a dictionary withstatus(the HTTP code, or-1if it couldn't connect) andmsg. That's why checkinginfo['status']is enough.- Always
changed=Falseandsupports_check_mode=True: it's an_infomodule. version_added: "1.2.0": this would be new functionality in the collection (the next minor version). If you publish it, follow the procedure in section 12.- The module runs on
api1: that's why127.0.0.1is correct there and wouldn't be on your computer.
Exercise 3. tests/integration/targets/nginx_upstream_server/tasks/main.yml:
---
- name: Create a test configuration file
ansible.builtin.copy:
dest: "{{ remote_tmp_dir | default('/tmp') }}/upstream.conf"
content: |
upstream test_backend {
server 10.0.0.1:80 weight=1;
server 10.0.0.2:80 weight=1;
}
mode: "0644"
- name: Take 10.0.0.1 out
aurora_store.infra.nginx_upstream_server:
path: "{{ remote_tmp_dir | default('/tmp') }}/upstream.conf"
upstream: test_backend
server: 10.0.0.1
state: down
register: test_out
- name: Take it out again
aurora_store.infra.nginx_upstream_server:
path: "{{ remote_tmp_dir | default('/tmp') }}/upstream.conf"
upstream: test_backend
server: 10.0.0.1
state: down
register: test_out_repeated
- name: Put it back
aurora_store.infra.nginx_upstream_server:
path: "{{ remote_tmp_dir | default('/tmp') }}/upstream.conf"
upstream: test_backend
server: 10.0.0.1
state: up
register: test_in
- name: Read the final file
ansible.builtin.slurp:
src: "{{ remote_tmp_dir | default('/tmp') }}/upstream.conf"
register: test_file
- name: Check the results
ansible.builtin.assert:
that:
- test_out is changed
- test_out.line == 'server 10.0.0.1:80 weight=1 down;'
- test_out_repeated is not changed
- test_in is changed
- "'down' not in (test_file.content | b64decode)"It's the same pattern as Molecule's verify.yml (Lesson 9.5): act, repeat to test idempotency, and check with assert. ansible-test integration runs the target in a test container.
Conclusion
A custom module is justified when a task needs "read, compare and change only if needed" logic that no existing module offers, and when --check and --diff must tell the truth. You've seen that a module is a Python program that receives its arguments as JSON and returns JSON, that AnsibleModule takes care of validating the arguments from argument_spec and provides check mode, diffs, atomic writes and backups, and that DOCUMENTATION, EXAMPLES and RETURN are as much part of the module as its code. With the logic separated into module_utils, nginx_upstream_server is tested with pytest in milliseconds, and ansible-test keeps watch over the documentation and compatibility. The aurora_store.infra 1.1.0 collection publishes it from Gitea, aurora-infra consumes it for the first time, and webservers.yml no longer depends on regular expressions that failed silently. But modules run on the servers; many of the extensions Aurora needs live on the control node, starting with the inventory: the staging one is still generated as a file from the Terraform outputs. In the next lesson, Dynamic Inventory, you'll replace hosts-terraform.yml with an inventory that builds itself, on every run, by querying AWS directly.
