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

  1. What can fail and what detects it
  2. The Ansible testing pyramid
  3. Molecule: concepts and current versions
  4. Installation
  5. Creating a scenario for the common role
  6. molecule.yml
  7. The test image with systemd
  8. prepare.yml and converge.yml
  9. verify.yml: checking with Ansible
  10. The test cycle
  11. Idempotency as a test
  12. Several platforms
  13. Molecule in the CI
  14. Going further: Testinfra, ansible-test and integration tests in staging

  1. 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.

  1. 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.

  1. 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 own requirements.yml.
  • destroy at the beginning: removes leftovers from a previous interrupted test.
  • create and prepare: 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.
  • destroy at 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 default driver (also called delegated), in which you write create.yml and destroy.yml. The Podman, Docker, Vagrant, EC2… drivers are in the molecule-plugins package.
  • Molecule no longer runs linters (the old lint: section is gone): that's done separately by ansible-lint, as in Lesson 9.4.
  • The scenario's Ansible configuration is written in an ansible: section (with cfg, env, executor and playbooks). The old keys in the provisioner: section (config_options, env, playbooks, options) are still accepted and migrated automatically, but new scenarios use ansible:.
  • molecule init scenario creates a skeleton designed for the default driver; it no longer lets you choose a driver when creating it. If you use another driver, you edit molecule.yml afterwards.
  • 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.

  1. 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.8

The 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 drivers

molecule 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.

  1. Creating a scenario for the common role

cd ~/aurora-infra/roles/common
molecule init scenario default
ls molecule/default/
converge.yml  create.yml  destroy.yml  molecule.yml  verify.yml

The 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:

rm molecule/default/create.yml molecule/default/destroy.yml

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

  1. 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: 1

Piece by piece:

  • driver.name: podman: the driver from molecule-plugins.
  • platforms: each element is an instance. With pre_build_image: false and dockerfile, Molecule builds an image from the scenario's Dockerfile.j2 template, using image as the base (the resulting image is called molecule_local/docker.io/library/ubuntu:24.04 and stays in Podman's cache for subsequent tests).
  • command: /sbin/init: the container's main process is systemd (on Ubuntu, /sbin/init is a link to systemd). Without this line, the driver starts a simple sleep and there would be no services.
  • systemd: always: asks Podman for systemd mode: it mounts the file systems systemd needs (/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.cfg options for Molecule's runs. Molecule generates its own ansible.cfg and doesn't use the project's (nor its inventory, nor its vaults): the test is isolated from the lab. You enable profile_tasks to see how long each task takes.
  • ansible.env: environment variables. ${MOLECULE_PROJECT_DIRECTORY} is the role's directory (roles/common): its parent is roles/, where Ansible will find the common role, and ../../collections holds the project's collections (community.general for timezone, ansible.posix for authorized_key and the callback, containers.podman for the connection).
  • prerun: false and role_name_check: 1: Molecule doesn't try to install dependencies or require a namespaced Galaxy name (the role is internal, Lesson 9.1).

  1. The test image with systemd

The 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; item is the platform, so the same template works for several base images (section 12).
  • Packages: systemd, systemd-sysv (provides /sbin/init) and dbus so that services and tools like timedatectl (used by community.general.timezone) work; python3 and python3-apt for the Ansible modules; sudo, because the role writes rules in sudoers.d and validates them with visudo; tzdata for the time zones; openssh-server, because the role hardens SSH and the test must check it. When it's installed, openssh-server generates the host keys, which sshd -t needs.
  • STOPSIGNAL SIGRTMIN+3: the signal with which systemd shuts down cleanly.
  • Nothing that the role should install (like curl or tree) is installed: the test must prove that the role does it.

  1. prepare.yml and converge.yml

8.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: true and minimal facts (like common.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_key module 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_hash simply doesn't get a password (default(omit)).

  1. verify.yml: checking with Ansible

Molecule 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.

  1. 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 destroy

molecule list shows something like this:

  Instance Name       Driver Name  Provisioner Name  Scenario Name  Created  Converged
 ─────────────────────────────────────────────────────────────────────────────────────
  common-ubuntu2404   podman       ansible           default        true     true

molecule 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

molecule 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: Successful

To investigate a failure, keep the instance: molecule test --destroy=never. Then molecule login, fix, molecule converge/verify, and finally molecule destroy.

  1. 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: config
molecule converge && molecule idempotence
CRITICAL Idempotence test failed because of the following tasks:
*  => common : Set the time zone

command 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.

  1. 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: always

molecule 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)"

  1. 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 invokes ansible-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, only default).
  • 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-check depends on tests, 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:

sudo -u runner podman info --format '{{.Host.CgroupsVersion}} {{.Host.CgroupManager}}'

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.

  1. Going further: Testinfra, ansible-test and integration tests in staging

14.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 == 0o440

It'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 drivers doesn't show podman. molecule-plugins is missing from the environment, or you're using a different molecule (from pipx or the system). Activate the project's .venv.
  • couldn't resolve module/action 'containers.podman...'. The collection from ci/requirements-tests.yml is missing, or the scenario's ANSIBLE_COLLECTIONS_PATH doesn't point to the project's collections/.
  • the role 'common' was not found. The scenario's ANSIBLE_ROLES_PATH doesn't include roles/. Check the path relative to ${MOLECULE_PROJECT_DIRECTORY}.
  • Services don't start in the container. Without command: /sbin/init and systemd: always, there's no systemd. With Docker, more options would be needed (mounting the cgroup, often privileged).
  • Missing privilege separation directory: /run/sshd. The prepare.yml task from section 8.1 is missing.
  • community.general.timezone fails in the container. It needs systemd and dbus running (packages in the image and systemd as the main process). Check with molecule login and timedatectl.
  • 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.yml must check the real effect (effective configuration, running service, content), not repeat what converge did.
  • Using latest for 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.yml the 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: nginx

verify.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

Module 2: Ansible Fundamentals

Module 3: Playbooks

Module 4: Roles

Module 5: Advanced Playbook Techniques

Module 6: Ansible Galaxy

Module 7: Ansible Tower, AWX and Automation Platform

Module 8: Ansible for DevOps

Module 9: Ansible Best Practices

Module 10: Advanced Ansible Topics

Module 11: Final Project

© Copyright 2026. All rights reserved