ansible-lint tells you whether the code is well written; it doesn't tell you whether it works. A role can meet the production profile and still fail to install what it promises, break a server's SSH or report changes on every run. Until now, the only way to find out in Aurora was to apply it to the lab and look. In this lesson you'll learn the testing layers an Ansible project has, from the cheapest to the most realistic, and you'll focus on Molecule, the standard tool for testing roles: it creates throwaway instances (here, containers with systemd), applies the role, checks that a second run changes nothing, verifies the result with assert and destroys everything. You'll write a complete scenario for the common role (which in Lesson 9.2 gained hardened SSH, sudo and keys: exactly the kind of change worth testing before touching a server), run it on two Ubuntu versions and finally fill the CI tests stage you left ready in Lesson 8.3.
Contents
- What can fail and what detects it
- The Ansible testing pyramid
- Molecule: concepts and current versions
- Installation
- Creating a scenario for the
commonrole molecule.yml- The test image with
systemd prepare.ymlandconverge.ymlverify.yml: checking with Ansible- The test cycle
- Idempotency as a test
- Several platforms
- Molecule in the CI
- Going further: Testinfra,
ansible-testand integration tests instaging
- What can fail and what detects it
Go over the failures you've seen (or caused) throughout the course and which tool would have detected them before they reached a server:
| Failure | Example in Aurora | Does --syntax-check detect it? |
ansible-lint? |
A real run? |
|---|---|---|---|---|
| Badly indented YAML | Exercise in Lesson 8.3 | Yes | Yes | Yes |
Module without FQCN, mode without quotes |
Conventions from Lesson 3.4 | No | Yes | Sometimes |
| Misspelled variable | nginx_prot instead of nginx_port |
No | No | Yes |
| Invalid module parameter | state: install |
No | Sometimes | Yes |
| Non-idempotent task | command without changed_when |
No | Sometimes | Yes, on the 2nd run |
| Configuration the service rejects | PermitRootLogin False (Lesson 9.2) |
No | No | Yes |
| The service starts but doesn't do what's expected | sshd still accepts passwords |
No | No | Only if it's verified |
The last three rows can only be detected by running the code and checking the result. Doing it on the lab is slow, leaves leftovers and may break it; doing it on production is unacceptable. Molecule solves exactly that: running and verifying on instances that are created for the test and destroyed afterwards.
- The Ansible testing pyramid
As with software in general, the tests of an Ansible project are organized in layers: at the bottom, many cheap and fast tests; at the top, few expensive and realistic ones.
flowchart TB
E["5. Integration in staging<br/>full site.yml on AWS + smoke tests<br/>(minutes to hours, financial cost)"]
D["4. Molecule per role<br/>throwaway containers: converge, idempotence, verify<br/>(minutes)"]
C["3. Check mode against an environment<br/>--check --diff (AWX, nightly and on every main)<br/>(minutes)"]
B["2. ansible-lint and yamllint<br/>(seconds)"]
A["1. --syntax-check<br/>(seconds)"]
E --- D --- C --- B --- A
| Layer | What it proves | What it doesn't prove | Where it runs in Aurora | Since |
|---|---|---|---|---|
1. --syntax-check |
The playbooks can be loaded | Nothing about their behavior | CI, syntax job |
8.3 |
| 2. Linters | Style, best practices, latent errors | That it works | pre-commit and CI, lint job |
9.4 |
3. --check --diff |
What would change in a real environment | That what changed works; some tasks can't be simulated | AWX: nightly check and on every main |
7.3, 8.3 |
| 4. Molecule | That a role applies, is idempotent and leaves the system as expected | The interaction between roles and with the real network | CI, tests job |
9.5 |
5. Integration in staging |
That everything works together in an environment similar to production | Differences in scale or data from production | Manual (Lesson 9.1); automated in the final project | 9.1 |
Each layer filters out errors for the next one: there's no point spending ten minutes of AWS time discovering an indentation error that --syntax-check finds in a second.
- Molecule: concepts and current versions
3.1. Concepts
| Concept | Meaning |
|---|---|
| Scenario | A set of tests for a role, in molecule/<name>/ inside the role. The main one is called default |
| Driver | What creates and destroys the instances: Podman, Docker, Vagrant, EC2… or the user themselves with their own playbooks |
| Platforms | The test instances (name, image, options) |
| Test sequence | The steps molecule test runs, in order |
| Scenario playbooks | create.yml/destroy.yml (if the driver doesn't provide them), prepare.yml, converge.yml, verify.yml, side_effect.yml, cleanup.yml |
The default molecule test sequence:
flowchart LR
dep["dependency"] --> cl1["cleanup"] --> d1["destroy"] --> syn["syntax"] --> cr["create"] --> pr["prepare"] --> cv["converge"] --> idem["idempotence"] --> se["side_effect"] --> ver["verify"] --> cl2["cleanup"] --> d2["destroy"]
dependency: installs the scenario's dependencies if it has its ownrequirements.yml.destroyat the beginning: removes leftovers from a previous interrupted test.createandprepare: create the instances and get them ready (prerequisite packages, simulated services…).converge: applies the role.idempotence: applies it again and fails if any task reports changes.verify: checks the result.destroyat the end: leaves nothing behind.
3.2. Molecule today
Molecule has changed quite a bit in recent years and many tutorials are out of date. What you need to know about the current versions (the 25 and 26 series, the latter being the one this lesson was written with):
- Drivers aren't included: Molecule only ships the
defaultdriver (also calleddelegated), in which you writecreate.ymlanddestroy.yml. The Podman, Docker, Vagrant, EC2… drivers are in themolecule-pluginspackage. - Molecule no longer runs linters (the old
lint:section is gone): that's done separately byansible-lint, as in Lesson 9.4. - The scenario's Ansible configuration is written in an
ansible:section (withcfg,env,executorandplaybooks). The old keys in theprovisioner:section (config_options,env,playbooks,options) are still accepted and migrated automatically, but new scenarios useansible:. molecule init scenariocreates a skeleton designed for thedefaultdriver; it no longer lets you choose a driver when creating it. If you use another driver, you editmolecule.ymlafterwards.- Molecule's collection and role installer (the preliminary step, prerun) can be disabled when the project already manages its dependencies, as Aurora does.
If you're working with another version and some option name doesn't match, check molecule --help and your version's documentation: the structure of this lesson (scenario, platforms, converge, idempotence, verify) is the same.
3.3. Which driver?
| Driver | Instances | Advantages | Drawbacks |
|---|---|---|---|
podman (molecule-plugins) |
Podman containers | Fast; no daemon; rootless containers; good systemd support |
It isn't a VM: no kernel of its own, kernel modules, real firewall… |
docker (molecule-plugins) |
Docker containers | Very widespread | Needs the Docker daemon; systemd requires more options |
vagrant (molecule-plugins) |
Local VMs | Behaves like a real server | Slow; needs virtualization (hard in CI) |
ec2, gce, azure (molecule-plugins) |
Cloud VMs | Same as production | Cost, credentials, time |
default |
Whatever you create in create.yml |
Total flexibility | You have to write the creation and destruction |
Aurora uses Podman: you already have it on your computer (Lesson 7.6) and on awx1, where the CI runner uses it to build the EE (Lesson 8.3). Remember what you saw with containers as test nodes in Lesson 8.1: they had no systemd, so you could only test package installation. Here you'll solve that with an image that boots systemd.
- Installation
In ci/requirements.txt, add at the end (the versions are the latest compatible with ansible-core 2.17 at the time of writing: like ansible-lint, the most recent versions of Molecule exclude the 2.17 series):
# Role testing (Lesson 9.5). Molecule 26.6.0 is the latest version that supports
# ansible-core 2.17; molecule-plugins provides the Podman driver.
molecule==26.6.0
molecule-plugins==26.7.8The Podman driver uses the containers.podman collection. It mustn't go in collections/requirements.yml (which AWX also installs and which defines the contents of aurora-ee): the tests mustn't bloat the execution environment. Create ci/requirements-tests.yml:
---
# Collections needed only by the Molecule tests (Lesson 9.5).
# They aren't part of aurora-ee and AWX doesn't install them.
collections:
- name: containers.podman
version: "1.21.2"Install everything in your project environment:
cd ~/aurora-infra
.venv/bin/pip install -r ci/requirements.txt
.venv/bin/ansible-galaxy collection install -r ci/requirements-tests.yml
source .venv/bin/activate
molecule --version
molecule driversmolecule drivers must list podman (and the others from molecule-plugins). The collection is installed in the project's collections/, like the rest, thanks to collections_path in ansible.cfg.
- Creating a scenario for the
common role
common roleThe skeleton is designed for the default driver (that's why it includes create.yml and destroy.yml with tasks to fill in). With the Podman driver, creation and destruction are provided by molecule-plugins, so delete those two files:
Aurora's scenario will have these files, which you'll write in the following sections:
roles/common/molecule/default/
├── molecule.yml configuration: driver, platforms, Ansible
├── Dockerfile.j2 test image with systemd
├── prepare.yml preliminary adjustments to the instances
├── converge.yml applies the role with test variables
└── verify.yml checks the result
molecule.yml
molecule.yml---
# Test scenario for the common role (Lesson 9.5).
driver:
name: podman
platforms:
- name: common-ubuntu2404
image: docker.io/library/ubuntu:24.04
dockerfile: Dockerfile.j2
pre_build_image: false
command: /sbin/init
systemd: always
ansible:
cfg:
defaults:
interpreter_python: auto_silent
callbacks_enabled: ansible.posix.profile_tasks
env:
# The role under test and the project's collections.
ANSIBLE_ROLES_PATH: ${MOLECULE_PROJECT_DIRECTORY}/..
ANSIBLE_COLLECTIONS_PATH: ${MOLECULE_PROJECT_DIRECTORY}/../../collections
# The dependencies are installed by the project (requirements.yml); Molecule mustn't do it.
prerun: false
# The role has no Galaxy namespace (it's internal): only warn.
role_name_check: 1Piece by piece:
driver.name: podman: the driver frommolecule-plugins.platforms: each element is an instance. Withpre_build_image: falseanddockerfile, Molecule builds an image from the scenario'sDockerfile.j2template, usingimageas the base (the resulting image is calledmolecule_local/docker.io/library/ubuntu:24.04and stays in Podman's cache for subsequent tests).command: /sbin/init: the container's main process issystemd(on Ubuntu,/sbin/initis a link tosystemd). Without this line, the driver starts a simplesleepand there would be no services.systemd: always: asks Podman for systemd mode: it mounts the file systemssystemdneeds (/run,/tmp, the cgroup…) and handles the stop signals. It's one of the reasons to prefer Podman in this case: no privileged container is needed.ansible.cfg:ansible.cfgoptions for Molecule's runs. Molecule generates its ownansible.cfgand doesn't use the project's (nor its inventory, nor its vaults): the test is isolated from the lab. You enableprofile_tasksto see how long each task takes.ansible.env: environment variables.${MOLECULE_PROJECT_DIRECTORY}is the role's directory (roles/common): its parent isroles/, where Ansible will find thecommonrole, and../../collectionsholds the project's collections (community.generalfortimezone,ansible.posixforauthorized_keyand the callback,containers.podmanfor the connection).prerun: falseandrole_name_check: 1: Molecule doesn't try to install dependencies or require a namespaced Galaxy name (the role is internal, Lesson 9.1).
- The test image with
systemd
systemdThe official ubuntu:24.04 image is minimal: it has no systemd, no Python, no sudo and no SSH server. Dockerfile.j2 builds one that resembles a server:
# Molecule managed: test image for the common role (Lesson 9.5).
FROM {{ item.image }}
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
systemd systemd-sysv dbus python3 python3-apt sudo tzdata \
openssh-server ca-certificates iproute2 \
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/*
STOPSIGNAL SIGRTMIN+3
CMD ["/sbin/init"]{{ item.image }}: the file is a Jinja template that Molecule renders for each platform;itemis the platform, so the same template works for several base images (section 12).- Packages:
systemd,systemd-sysv(provides/sbin/init) anddbusso that services and tools liketimedatectl(used bycommunity.general.timezone) work;python3andpython3-aptfor the Ansible modules;sudo, because the role writes rules insudoers.dand validates them withvisudo;tzdatafor the time zones;openssh-server, because the role hardens SSH and the test must check it. When it's installed,openssh-servergenerates the host keys, whichsshd -tneeds. STOPSIGNAL SIGRTMIN+3: the signal with whichsystemdshuts down cleanly.- Nothing that the role should install (like
curlortree) is installed: the test must prove that the role does it.
prepare.yml and converge.yml
prepare.yml and converge.yml8.1. prepare.yml
---
# Leaves the instances like a freshly installed server before applying the role.
- name: Prepare the test instances
hosts: all
gather_facts: false
tasks:
# No module waits for systemd to finish booting: the command is justified.
- name: Wait for systemd to finish booting # noqa: command-instead-of-module
ansible.builtin.command:
cmd: systemctl is-system-running --wait
register: common_test_systemd
changed_when: false
# "degraded" (code 1) is normal in a container: some unit doesn't apply.
failed_when: common_test_systemd.rc not in [0, 1]
- name: Create the sshd privilege separation directory
ansible.builtin.file:
path: /run/sshd
state: directory
owner: root
group: root
mode: "0755"The second task deserves an explanation, because it's a typical case of a "difference between the test and reality". sshd -t (used by the role's validate and handler) requires /run/sshd to exist. On a real server, that directory always exists while the SSH service is running, and it is running, because Ansible connects over SSH. In the container, Ansible connects with podman exec, the SSH service hasn't started yet and the directory doesn't exist: the first run would fail with Missing privilege separation directory: /run/sshd (you'll see it if you comment out the task). The preparation reproduces the conditions of the real server; the role isn't modified to suit the test.
Molecule instances are handled as root (the container user), so prepare.yml doesn't need become.
8.2. converge.yml
---
# Applies the common role with test data (Lesson 9.5).
- name: Converge
hosts: all
become: true
gather_facts: true
gather_subset:
- min
vars:
common_packages:
- curl
- tree
common_timezone: Europe/Madrid
common_organization: Aurora Store (testing)
common_env: molecule
common_domain: test.aurora-store.example
common_contact: [email protected]
common_facts_name: aurora
common_managed_by: molecule
common_users:
- name: test
comment: Test user
admin: true
ssh_keys:
- ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIEZpY3RpY2lhUHJ1ZWJhTW9sZWN1bGUwMDAwMDAwMDAw test@molecule
- name: former
state: absent
common_automation_user: automation
common_automation_keys:
- ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIEF1dG9tYXRpemFjaW9uRmljdGljaWEwMDAwMDAwMDAw automation@molecule
common_automation_key_options: 'from="10.0.0.1"'
roles:
- role: common- The play reproduces how Aurora uses the role:
become: trueand minimal facts (likecommon.yml, Lesson 5.8). - The test variables exercise all the interesting branches of the role: an administrator with a key, a user that must be removed, and the automation account with key options. They're fictitious data (the keys don't correspond to any private key; the
authorized_keymodule doesn't validate that they do). - There are no passwords and no Vault: the scenario doesn't use the project inventory. A user without
password_hashsimply doesn't get a password (default(omit)).
verify.yml: checking with Ansible
verify.yml: checking with AnsibleMolecule supports several verifiers; the default one is Ansible: a playbook that checks the state with read-only modules and assert (Lesson 3.7). The advantage is that there's no other tool to learn.
---
# Checks that the common role has left the system as expected (Lesson 9.5).
- name: Verify the common role
hosts: all
become: true
gather_facts: false
tasks:
- name: Get the system users
ansible.builtin.getent:
database: passwd
- name: Check the team users and the automation account
ansible.builtin.assert:
that:
- "'test' in ansible_facts['getent_passwd']"
- "'former' not in ansible_facts['getent_passwd']"
- "'automation' in ansible_facts['getent_passwd']"
fail_msg: The users are not the expected ones
- name: Get the members of the sudo group
ansible.builtin.getent:
database: group
key: sudo
- name: Check that the test administrator is in the sudo group
ansible.builtin.assert:
that: "'test' in ansible_facts['getent_group']['sudo'][2].split(',')"
- name: Read the users' authorized keys
ansible.builtin.slurp:
src: "/home/{{ item }}/.ssh/authorized_keys"
loop:
- test
- automation
register: common_test_keys
- name: Check the keys and their options
ansible.builtin.assert:
that:
- "'test@molecule' in (common_test_keys.results[0].content | b64decode)"
- "(common_test_keys.results[1].content | b64decode).startswith('from=\"10.0.0.1\"')"
- name: Get the effective SSH configuration
ansible.builtin.command:
cmd: sshd -T
register: common_test_sshd
changed_when: false
- name: Check the SSH hardening
ansible.builtin.assert:
that:
- "'permitrootlogin no' in common_test_sshd.stdout_lines"
- "'passwordauthentication no' in common_test_sshd.stdout_lines"
- "'maxauthtries 3' in common_test_sshd.stdout_lines"
- name: Check that the sudo configuration is valid
ansible.builtin.command:
cmd: visudo -c
changed_when: false
- name: Get the role's sudo rules
ansible.builtin.stat:
path: /etc/sudoers.d/common
register: common_test_sudoers
- name: Check the permissions of the sudo rules
ansible.builtin.assert:
that:
- common_test_sudoers.stat.exists
- common_test_sudoers.stat.mode == '0440'
- name: Get the time zone
ansible.builtin.stat:
path: /etc/localtime
register: common_test_localtime
- name: Check the time zone
ansible.builtin.assert:
that: common_test_localtime.stat.lnk_source is search('Europe/Madrid')
- name: Read the welcome message
ansible.builtin.slurp:
src: /etc/motd
register: common_test_motd
- name: Check the welcome message
ansible.builtin.assert:
that: "'Aurora Store (testing)' in (common_test_motd.content | b64decode)"
- name: Read the local facts
ansible.builtin.setup:
filter: ansible_local
- name: Check the local facts
ansible.builtin.assert:
that: ansible_local['aurora']['general']['env'] == 'molecule'Notice the pattern: each check is a query (getent, slurp, stat, command with changed_when: false, setup) followed by an assert with clear messages. And what's verified isn't "that the task ran" (converge already knows that), but the effect that matters: that sshd effectively doesn't accept passwords (sshd -T combines all the configuration files), that sudo effectively is valid, that the time zone effectively is the one requested.
- The test cycle
10.1. Step by step, while you develop
While you're writing a scenario or changing the role, it's more convenient to run the steps separately and keep the instance between them. From roles/common (with the .venv activated):
molecule create # builds the image and starts the container
molecule list # instances, driver and state
molecule prepare
molecule converge # applies the role (you can repeat it after each change)
molecule login # a shell inside the instance, to investigate
molecule verify
molecule idempotence
molecule destroymolecule list shows something like this:
Instance Name Driver Name Provisioner Name Scenario Name Created Converged
─────────────────────────────────────────────────────────────────────────────────────
common-ubuntu2404 podman ansible default true truemolecule login is the most useful diagnostic tool: inside, you can look at /etc/ssh/sshd_config.d/00-common.conf, run sshd -T, systemctl status ssh or cat /etc/sudoers.d/common. If there are several platforms, you specify which one with molecule login -h common-ubuntu2404.
10.2. The full test
It runs the whole sequence and destroys the instances at the end, even if something fails. An excerpt of the output:
INFO default ➜ converge: Executing
...
PLAY RECAP *********************************************************************
common-ubuntu2404 : ok=27 changed=13 unreachable=0 failed=0 skipped=3 rescued=0 ignored=0
INFO default ➜ idempotence: Executing
...
INFO default ➜ idempotence: Executed: Successful
INFO default ➜ verify: Executing
...
TASK [Check the SSH hardening] *************************************************
ok: [common-ubuntu2404] => {
"changed": false,
"msg": "All assertions passed"
}
...
INFO default ➜ destroy: Executed: SuccessfulTo investigate a failure, keep the instance: molecule test --destroy=never. Then molecule login, fix, molecule converge/verify, and finally molecule destroy.
- Idempotency as a test
The idempotence step applies the role a second time and fails if any task reports changed. It's the automatic check of the golden rule you've followed since Module 4 ("the second run reports changed=0"). To see it fail, temporarily change the time zone task in roles/common/tasks/main.yml to a command:
- name: Set the time zone
ansible.builtin.command:
cmd: "timedatectl set-timezone {{ common_timezone }}"
tags: configcommand always reports a change (Lesson 1.4), so the role is no longer idempotent, and Molecule detects it without anyone having to look at the output. (ansible-lint would also have detected it with no-changed-when; a changed_when: false would "silence" it without making it correct: that's why idempotency is tested by running.) Undo the change with git checkout roles/common/tasks/main.yml.
This step is especially valuable in Aurora because of the handlers: a task that reports changes on every run would trigger the SSH or nginx reload on every run.
- Several platforms
The common role declares in its meta/main.yml that it supports Ubuntu noble (24.04). If you wanted to use it on servers with Ubuntu 22.04 (jammy) too, would it work? With Molecule you only need to add a platform; the same Dockerfile.j2 builds its image:
platforms:
- name: common-ubuntu2404
image: docker.io/library/ubuntu:24.04
dockerfile: Dockerfile.j2
pre_build_image: false
command: /sbin/init
systemd: always
- name: common-ubuntu2204
image: docker.io/library/ubuntu:22.04
dockerfile: Dockerfile.j2
pre_build_image: false
command: /sbin/init
systemd: alwaysmolecule test creates both instances, applies the role to both (in parallel, like any play) and verifies them with the same verify.yml. If both pass, you can add jammy to platforms in meta/main.yml on solid grounds. If one fails, the output tells you which one and in which task. That's how you maintain a role for several distributions: every platform declared in meta/main.yml should be in the scenario. (For a different family, such as Rocky Linux, you'd also need a Dockerfile.j2 that uses dnf; Molecule's default one, which would be used without yours, already distinguishes between apt, dnf, yum, zypper and apk.)
Commit the scenario:
cd ~/aurora-infra
git add roles/common/molecule/ ci/requirements.txt ci/requirements-tests.yml
git commit -m "Tests: Molecule scenario for the common role (Ubuntu 24.04 and 22.04)"
- Molecule in the CI
13.1. The tests job
In Lesson 8.3 you left the tests job iterating over roles/*/ and running molecule test wherever there was a molecule/ directory. The tools and the collections were missing. In .gitea/workflows/ci.yml:
tests:
name: Tests
runs-on: aurora-runner
needs: syntax
steps:
- name: Check out the repository
uses: actions/checkout@v4
- name: Set up the tools, the collections and the roles
run: |
python3 -m venv .venv
.venv/bin/pip install --quiet -r ci/requirements.txt
.venv/bin/ansible-galaxy collection install -r collections/requirements.yml
.venv/bin/ansible-galaxy collection install -r ci/requirements-tests.yml
.venv/bin/ansible-galaxy role install -r roles/requirements.yml
- name: Run the Molecule scenarios of the roles that have them
run: |
export PATH="$PWD/.venv/bin:$PATH"
for role in roles/*/; do
if [ -d "${role}molecule" ]; then
echo "== $role"
(cd "$role" && molecule test --all)
fi
done
echo "Tests finished"export PATH=...: Molecule invokesansible-playbook, which must be the one in the.venv(the pinned version), not some other one on the system.molecule test --all: all the scenarios of each role (today, onlydefault).- The loop doesn't change: when you add a scenario to another role, the CI will run it without touching this file, as Lesson 8.3 promised.
- If a scenario fails, the subprocess exits with an error, the step fails and, since
lab-checkdepends ontests, the check in AWX isn't launched.
13.2. Runner requirements
The runner on awx1 runs jobs as the runner user with rootless Podman (it already uses it to build the EE). Rootless containers with systemd need the system to delegate the cgroups to the user, which Ubuntu 24.04 does by default with cgroups v2 and the persistent session (linger) you enabled in Lesson 8.3. If creation failed with cgroups errors, check on awx1:
It must show v2 systemd. The first run takes longer (downloading ubuntu:24.04 and ubuntu:22.04 and building the images); the following ones use the runner user's Podman cache.
Push the changes on a branch, open the pull request and check in Actions that the tests job runs the common scenario and finishes green. With the main protection from Lesson 9.4 (which included Tests among the required checks), no change that breaks the common role can be merged.
13.3. What about the other roles?
| Role | Molecule with containers? | Notes |
|---|---|---|
common |
Yes (done) | |
postgresql |
Yes | Image with systemd; verify with postgresql_ping and a query (Exercise 2) |
aurora_app |
Yes, with its nginx dependency |
ANSIBLE_ROLES_PATH must include galaxy_roles/; verify with uri against localhost |
nginx |
In its own repository (ansible-role-nginx) |
Exercise 1 |
docker |
Hard | Docker inside a container needs privileges; better the vagrant driver or default with a VM |
aurora_catalog |
Hard | Depends on docker |
aurora_catalog_k8s |
Not with system containers | Needs a cluster: the default driver with a throwaway cluster (for example, kind) in create.yml |
The rule of thumb: start with the most used and most sensitive roles (common, which touches access to all the servers, was the obvious first one) and add scenarios when a role changes or fails.
- Going further: Testinfra,
ansible-test and integration tests in staging
ansible-test and integration tests in staging14.1. Testinfra
Testinfra (the pytest-testinfra package) is an alternative verifier: the checks are written in Python, as pytest tests, with objects that represent the system (host.file, host.service, host.user, host.run…). In Molecule it's enabled with verifier: name: testinfra and the tests go in molecule/default/tests/:
def test_sshd_rejects_passwords(host):
configuration = host.run("sshd -T").stdout
assert "passwordauthentication no" in configuration
def test_sudo_rules(host):
rules = host.file("/etc/sudoers.d/common")
assert rules.exists
assert rules.mode == 0o440It's more expressive for complex logic and familiar to people who program in Python; in exchange, it adds another tool and another language. Aurora sticks with the Ansible verifier.
14.2. ansible-test for collections
Collections (like aurora_store.infra, Lesson 6.5) have their own testing tool, included in ansible-core: ansible-test.
| Type | Command | What it tests |
|---|---|---|
| Sanity | ansible-test sanity --docker default |
Code quality of plugins and modules: documentation, Python compatibility, imports, pylint… |
| Unit | ansible-test units --docker default |
pytest tests of plugins and modules |
| Integration | ansible-test integration --docker default |
Test playbooks (targets) in tests/integration/targets/ |
ansible-test must be run inside the ansible_collections/<namespace>/<name>/ path (that's why you created the collection in ~/ansible_collections/aurora_store/infra), and --docker runs the tests in containers with all the necessary Python versions (it supports Podman). Justified sanity exceptions are recorded in tests/sanity/ignore-<version>.txt, which the ansible-lint sanity rule checks. It will make sense in the next module, when the collection includes modules and plugins written in Python.
14.3. Integration tests in staging
Molecule tests one role in isolation. The top layer of the pyramid tests everything together: staging-provision.yml creates the environment and applies site.yml (Lesson 9.1); then some smoke tests check what a customer sees (the page responds on the public IP, shows the expected version, the website reaches the database), and the environment is destroyed. Automating it requires AWS credentials and the staging Vault password on the system that runs it, the OpenTofu state in a remote backend (Lesson 8.5) and the dynamic inventory (Lesson 10.2): you'll set it up in the final project, as a scheduled run (for example, every night) and as a prerequisite for each release to production.
Common Mistakes and Tips
molecule driversdoesn't showpodman.molecule-pluginsis missing from the environment, or you're using a differentmolecule(frompipxor the system). Activate the project's.venv.couldn't resolve module/action 'containers.podman...'. The collection fromci/requirements-tests.ymlis missing, or the scenario'sANSIBLE_COLLECTIONS_PATHdoesn't point to the project'scollections/.the role 'common' was not found. The scenario'sANSIBLE_ROLES_PATHdoesn't includeroles/. Check the path relative to${MOLECULE_PROJECT_DIRECTORY}.- Services don't start in the container. Without
command: /sbin/initandsystemd: always, there's nosystemd. With Docker, more options would be needed (mounting the cgroup, oftenprivileged). Missing privilege separation directory: /run/sshd. Theprepare.ymltask from section 8.1 is missing.community.general.timezonefails in the container. It needssystemdanddbusrunning (packages in the image andsystemdas the main process). Check withmolecule loginandtimedatectl.- Modifying the role so that it passes the test. If the role works on the servers and fails in the container, the problem is in the instance's preparation (image,
prepare.yml), not in the role. - Tests that only check that "the task ran".
verify.ymlmust check the real effect (effective configuration, running service, content), not repeat whatconvergedid. - Using
latestfor images. A base image that changes on its own changes the test results without your code changing. For maximum reproducibility, pin the base image by digest. - Tip: when you fix a bug in a role, first add to
verify.ymlthe check that would have caught it, confirm that it fails, and then fix it. That way the bug won't come back without you knowing.
Exercises
Exercise 1: a scenario for ansible-role-nginx
In the ~/ansible-role-nginx repository, create a default scenario that applies the role in static site mode (nginx_site_name: test, nginx_root: /var/www/test) and verifies that nginx is running, that it responds on localhost with status code 200 and that the Server header doesn't show the version (Lesson 9.2). Think about what you need in prepare.yml so that there's something to serve.
Exercise 2: a scenario for postgresql
Sketch out the scenario for the postgresql role in aurora-infra: which packages you'd add to the image, which variables you'd put in converge.yml and what you'd check in verify.yml.
Exercise 3: a test that must fail
You want to make sure the SSH template's validate really protects you. Describe how you'd prove with Molecule that, if common_ssh_max_auth_tries: "three" is passed, the role fails and the previous configuration file remains intact.
Solutions
Exercise 1. In ~/ansible-role-nginx: molecule init scenario default, delete create.yml and destroy.yml, and copy molecule.yml and Dockerfile.j2 from the common scenario (in ANSIBLE_ROLES_PATH, the role's parent is ~, so the role directory should be called nginx or the path adjusted; and the necessary collections, community.general for ufw and containers.podman, are installed with a requirements.yml of its own). prepare.yml: create /var/www/test with a test index.html (the role configures the site, it doesn't publish content). converge.yml:
- name: Converge
hosts: all
become: true
gather_facts: false
vars:
nginx_site_name: test
nginx_server_name: localhost
nginx_root: /var/www/test
roles:
- role: nginxverify.yml:
- name: Verify the nginx role
hosts: all
gather_facts: false
tasks:
- name: Request the test page
ansible.builtin.uri:
url: http://localhost/
return_content: true
register: nginx_test_web
- name: Check the response and the Server header
ansible.builtin.assert:
that:
- nginx_test_web.status == 200
- "'Test' in nginx_test_web.content"
- nginx_test_web.server == 'nginx'A second scenario, loadbalancer, that tests the mode with nginx_upstream_servers is also a good idea (site.conf.j2 changes a lot in that mode). And CI in the role's repository (a .gitea/workflows/ci.yml with ansible-lint and molecule test --all) would make every new version of the role reach aurora-infra already tested.
Exercise 2. Image: the same Dockerfile.j2 (the role installs postgresql, python3-psycopg2 and acl, so they aren't added to the image). converge.yml: postgresql_version: 16, postgresql_conf_name: test, postgresql_users with a test user with a password, postgresql_databases with a test database owned by that user, postgresql_hba_clients: ["10.0.0.5"]. verify.yml: community.postgresql.postgresql_ping as postgres (with become_user: postgres) and another one with login_user: test, login_password and login_host: 127.0.0.1 (it checks the password and pg_hba.conf); slurp of pg_hba.conf to check that 10.0.0.5/32 appears; and a community.postgresql.postgresql_query with SHOW max_connections to verify that the conf.d parameters are applied. Version 16 is the one in Ubuntu 24.04: for the 22.04 platform you'd have to change postgresql_version (14), which shows that this value depends on the distribution.
Exercise 3. An additional scenario, validation (molecule init scenario validation), with a converge.yml in two plays: the first applies the role with correct values; the second applies it again with common_ssh_max_auth_tries: "three" inside a block with a rescue that records that it failed (set_fact: common_test_failed: true). That scenario's test sequence is defined without idempotence (in scenario.test_sequence), and verify.yml checks with assert that common_test_failed is defined (in a test like this it's saved to a file on the instance, because verify is a separate run) and that /etc/ssh/sshd_config.d/00-common.conf still contains MaxAuthTries 3. (With argument_specs, if the variable is declared as int, the role's validation would fail even earlier, in the argument validation task: that's also a good test that this safety net works.)
Conclusion
With this lesson you close Module 9, and Aurora Store's testing pyramid is complete in its automated layers: syntax check, yamllint and ansible-lint, check mode in AWX and, now, Molecule. You know its concepts (scenarios, drivers, platforms, test sequence) and the current state of the tool (drivers in molecule-plugins, the ansible: section, no built-in linters, pinned versions compatible with ansible-core 2.17). You've written a complete scenario for the common role with the Podman driver and an image with systemd, a preparation that reproduces the conditions of a real server, a converge.yml that exercises all its branches and a verify.yml that checks the real effects (effective SSH, valid sudo, keys, time zone, facts); you've tested it on Ubuntu 24.04 and 22.04, you've seen how idempotency becomes an automated test, and the CI tests stage now runs the scenarios on every change. You also know when to turn to Testinfra, to ansible-test for collections and to integration tests in staging. Aurora Store now has a repository organized by environment, hardened, tuned and with continuously verified quality. Up to this point you've always used what Ansible and its collections offer; but the time will come when you need something no module does, like talking to the store's internal API or computing the load balancer configuration without unreadable Jinja expressions. In Module 10: Advanced Ansible Topics you'll start with the Custom Modules lesson, where you'll write your own modules in Python, with their documentation, their check mode and their tests, and add them to the aurora_store.infra collection.
Ansible Course: From Beginner to Advanced
Module 1: Introduction to Ansible
- What Is Ansible?
- Installing Ansible
- Setting Up the Practice Lab
- Ansible Architecture
- Basic Ansible Commands
Module 2: Ansible Fundamentals
- Inventory Files
- Inventory Variables: group_vars and host_vars
- Configuring Ansible (ansible.cfg)
- Ad Hoc Commands
- Ansible Modules
- Collections and Fully Qualified Names (FQCN)
Module 3: Playbooks
- Introduction to Playbooks
- Essential YAML for Ansible
- Writing Your First Playbook
- Playbook Structure
- Variables and Facts
- Conditionals and Loops
- Registering Results and Debugging Playbooks
Module 4: Roles
- Introduction to Roles
- Creating Roles
- Role Directory Structure
- Using Roles in Playbooks
- Reusing Tasks: include and import
- Role Dependencies and Argument Validation
Module 5: Advanced Playbook Techniques
- Handlers
- Jinja2 Templates
- Filters and Lookups
- Ansible Vault
- Error Handling
- Tags and Selective Execution
- Rolling Deployments and Delegation
- Optimizing Playbooks
Module 6: Ansible Galaxy
- What Is Ansible Galaxy?
- Using Ansible Galaxy
- Managing Dependencies with requirements.yml
- Creating and Sharing Roles
- Creating Your Own Collections
Module 7: Ansible Tower, AWX and Automation Platform
- Introduction to Ansible Tower and AWX
- Installing AWX
- Using AWX: Job Templates and Jobs
- Managing Projects and Inventories
- Credentials, Permissions (RBAC) and Workflows
- Execution Environments and ansible-navigator
Module 8: Ansible for DevOps
- Ansible and Docker
- Ansible and Kubernetes
- CI/CD with Ansible
- Ansible in Cloud Environments
- Ansible and Terraform
Module 9: Ansible Best Practices
- Code Organization
- Security Best Practices
- Performance Tuning
- Code Quality: ansible-lint and yamllint
- Testing Ansible Code with Molecule
Module 10: Advanced Ansible Topics
- Custom Modules
- Dynamic Inventory
- Ansible Plugins
- The Ansible API and ansible-runner
- Event-Driven Ansible
