If you maintain Ansible roles and the only test is “run it against staging and see what breaks”, Molecule is the missing piece. It spins up a throwaway container, applies your role to it, runs the role a second time to prove nothing changes, then asserts the end state and destroys everything. By the end of this article you will have a molecule/default/ scenario running against two distro images, a real idempotence check, ansible-lint in the same run, and molecule test failing pull requests in GitHub Actions.
What you’ll accomplish
- Install Molecule with the container driver and confirm the driver is registered.
- Scaffold a
molecule/default/scenario for an existing role and understand every file in it. - Run the lifecycle step by step (
create,converge,idempotence,verify,destroy) and know what each one proves. - Write real assertions in
verify.ymland make the idempotence step fail loudly on the tasks that deserve it. - Test the same role against two distro images in one scenario and run the whole thing on every push.
Prerequisites
ansible-core2.16 or newer and Python 3.10+. Molecule follows Ansible’s support window closely, so an EOLansible-coreis the first thing to rule out when something behaves oddly.- Docker or Podman working for your user. Rootless Podman is fine and is what most people should use on a laptop; rootless Docker also works. If
docker psneedssudo, fix that before touching Molecule. - An existing role you want to test. If your repo is still one long playbook, split it into roles first — see Ansible roles and inventory layout.
- A virtualenv. Molecule,
ansible-coreand the driver plugin should live in one isolated environment, not in system Python.
Two honest caveats about drivers. First, the container drivers ship in a separate package (molecule-plugins), not in molecule itself — installing molecule alone gets you no docker driver. Second, containers are not virtual machines: no real init system by default, no kernel modules, no systemctl unless you go out of your way. Roles that manage services need the extra container configuration shown below, and roles that tune the kernel are simply not testable this way.
How it works
Molecule organises everything around a scenario — a directory holding the config plus the playbooks for each phase of the lifecycle. The default scenario lives at molecule/default/ inside the role.
molecule.yml declares the driver and the platforms (the containers to create). converge.yml is the playbook that applies the role under test. verify.yml is the playbook that asserts the result. Molecule generates a dynamic inventory pointing at the containers it created, so your role runs against them exactly as it would against real hosts.
The value is in the sequence, not any single step. molecule test runs the whole thing in order and destroys the instance at the end regardless of outcome:
The step most roles fail on is idempotence. Molecule runs converge a second time and parses Ansible’s recap: if any host reports a non-zero changed= count, the step fails and names the offending tasks. That is a genuinely hard bar. A role that runs command: without a creates: guard, templates a file containing a timestamp, or restarts a service unconditionally will fail it — and should, because those are the roles that cause surprise restarts in production.
Step-by-step
- Install Molecule and the container driver. The drivers are in
molecule-plugins; pick the extra that matches your container engine.
python3 -m venv ~/.venvs/molecule
source ~/.venvs/molecule/bin/activate
python3 -m pip install --upgrade pip
python3 -m pip install "molecule" "molecule-plugins[docker]" ansible-core ansible-lint
Confirm the versions and that the driver actually registered:
molecule --version
molecule drivers
You should see a Molecule version, the ansible-core version underneath it, and docker in the driver list. If molecule drivers shows only default, the plugins package did not install into the same environment — check which molecule and pip list | grep molecule.
The Docker driver drives containers through Ansible modules, so install the collection too:
ansible-galaxy collection install community.docker
- Scaffold the scenario inside your role. Run this from the role’s root directory (the one containing
tasks/):
cd ~/ansible/roles/nginx
molecule init scenario default
Expected output ends with a line naming the created directory. Confirm the layout:
find molecule -type f | sort
molecule/default/converge.yml
molecule/default/create.yml
molecule/default/destroy.yml
molecule/default/molecule.yml
molecule/default/verify.yml
- Write
molecule.yml. Replace the generated file with a container-driver configuration. Two platforms means the role is tested on two distros in the same run.
---
dependency:
name: galaxy
driver:
name: docker
platforms:
- name: nginx-debian12
image: docker.io/library/debian:12
pre_build_image: true
groups:
- debian
- name: nginx-rocky9
image: docker.io/rockylinux/rockylinux:9
pre_build_image: true
groups:
- rhel
provisioner:
name: ansible
verifier:
name: ansible
pre_build_image: true tells Molecule to pull the image as-is instead of building a derived image from a Dockerfile template. The groups keys land in the generated inventory, so when: inventory_hostname in groups['debian'] works in your playbooks.
When the create and destroy playbooks are handled by the driver, you can delete the generated create.yml and destroy.yml — the driver supplies its own.
- Point
converge.ymlat the role. This is a normal playbook; nothing Molecule-specific about it beyond the host pattern.
---
- name: Converge
hosts: all
become: true
tasks:
- name: Apply the role under test
ansible.builtin.include_role:
name: nginx
vars:
nginx_worker_processes: 2
- Bring up the containers and apply the role. Run the two steps separately the first time so you can see where a failure comes from.
molecule create
molecule list
molecule list prints a table with both instance names, the driver, and a Created column reading true. Then:
molecule converge
Success looks like a normal Ansible run ending in a PLAY RECAP with failed=0 for both hosts. The container stays up afterwards, which is the whole point of running converge on its own.
- Prove idempotence. With the instance still converged:
molecule idempotence
A pass prints an idempotence success line and nothing else. A failure prints the recap plus the list of tasks that reported changed, which is exactly the debugging information you need:
CRITICAL Idempotence test failed because of the following tasks:
* [nginx-debian12] => nginx : Reload nginx configuration
- Write assertions in
verify.yml. The generated file assertstrue, which proves nothing. Replace it with checks that would actually catch a regression:
---
- name: Verify
hosts: all
become: true
gather_facts: true
tasks:
- name: Collect the nginx service state
ansible.builtin.service_facts:
- name: Read the rendered configuration
ansible.builtin.slurp:
src: /etc/nginx/nginx.conf
register: nginx_conf
- name: The package must be installed and the config rendered
ansible.builtin.assert:
that:
- "'nginx.service' in ansible_facts.services"
- (nginx_conf.content | b64decode) is search('worker_processes 2;')
fail_msg: nginx is not installed or worker_processes was not templated
success_msg: nginx package and configuration verified
- name: The site must answer on localhost
ansible.builtin.uri:
url: http://127.0.0.1/
status_code: 200
Run it:
molecule verify
Expected: a play recap with failed=0 and your success_msg in the output. If you prefer Python-based assertions, set verifier: name: testinfra in molecule.yml and put pytest files under molecule/default/tests/ — the Ansible verifier is the default because most role authors already know the assert module, but testinfra reads better for dense system-state checks.
- Add ansible-lint. Molecule no longer runs a linter for you, so run it as its own command. Configure it once in a file named
.ansible-lintat the role root:
---
profile: production
exclude_paths:
- .cache/
- molecule/
ansible-lint
Expected on a clean role: Passed: 0 failure(s), 0 warning(s).
- Wire it into GitHub Actions. Create
.github/workflows/molecule.yml:
---
name: molecule
on:
push:
branches: [main]
pull_request:
jobs:
molecule:
runs-on: ubuntu-24.04
strategy:
fail-fast: false
matrix:
scenario: [default]
steps:
- name: Check out the role
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.12'
- name: Install Molecule and the docker driver
run: |
python3 -m pip install --upgrade pip
python3 -m pip install molecule "molecule-plugins[docker]" ansible-core ansible-lint
ansible-galaxy collection install community.docker
- name: Lint
run: ansible-lint
- name: Run the molecule scenario
run: molecule test --scenario-name ${{ matrix.scenario }}
env:
PY_COLORS: '1'
ANSIBLE_FORCE_COLOR: '1'
The GitHub-hosted ubuntu-24.04 runner already has a working Docker daemon, so there is no service container or privileged setup to arrange. Adding a second scenario later is a one-word change to the matrix.
Validate it works
Run the full sequence exactly as CI will:
molecule test
Expected: every action in the sequence prints a header, the idempotence step passes, verify reports failed=0 on both hosts, and the run ends with both containers destroyed. Confirm nothing was left behind:
molecule list
docker ps -a --filter name=nginx-
molecule list should show Created: false for both instances and docker ps -a should return only the header row.
To see the ordered action list without running anything:
molecule matrix test
And when a run fails and you want the container to inspect:
molecule test --destroy=never
docker exec -it nginx-debian12 bash
Troubleshooting
Idempotence fails on a command or shell task. This is the classic one. An unguarded ansible.builtin.command reports changed on every run by definition. Fix it properly with a creates: argument so the task is skipped when the work is already done, or changed_when: derived from the command’s own output. Silencing it with changed_when: false on a task that genuinely mutates the system is a lie that will cost you later — the recap will read clean while the task keeps restarting a service on every run.
Idempotence fails on a template. A template: task that renders a timestamp, a random value, or an unsorted dictionary produces different bytes each run. Sort your loops (| dictsort, | sort), drop the generated-on comment, and the task settles.
systemctl fails with “System has not been booted with systemd as init system”. The container has no PID 1 init. For roles that manage services, the platform needs to run systemd, which means a privileged container with the cgroup filesystem mounted:
platforms:
- name: nginx-rocky9
image: docker.io/rockylinux/rockylinux:9
pre_build_image: true
privileged: true
command: /usr/sbin/init
cgroupns_mode: host
volumes:
- /sys/fs/cgroup:/sys/fs/cgroup:rw
You also need an image that actually has systemd installed — the stock Debian and Ubuntu images do not. Note the trade-off: privileged containers hand the workload broad access to the host, which is acceptable for a throwaway CI container and not acceptable anywhere else.
molecule drivers does not list docker. The plugins package landed in a different Python environment from molecule. Activate the virtualenv and reinstall both packages together. If you upgraded from an older setup, uninstall any standalone molecule-docker or molecule-podman package first — the old and new packages register the same entry points and the conflict produces confusing import errors.
A failed run leaves containers behind. molecule test destroys by default, but a hard interrupt can strand a container. Clean up with molecule destroy, and use molecule reset to clear the cached ephemeral state directory if Molecule keeps insisting an instance exists when it does not.
When this is the wrong approach
Molecule tests a role in isolation against a blank container. That is the right shape for a role that installs a package, renders config and starts a daemon. It is the wrong shape for several things people try to use it for.
It does not test your inventory. A role that passes every scenario can still explode in production because group_vars/ set a variable nobody expected. Nor does it validate secrets handling — for that, see Ansible Vault for secrets.
It cannot test anything the kernel owns: kernel modules, sysctl values that containers do not namespace, storage layout, firewall rules that need real netfilter state. Those need a VM driver or a real host.
And it is not an integration test. If the actual risk in your stack is that three roles interact badly across five hosts, a per-role container scenario will not find it — you need a staging environment that mirrors production topology. Molecule is the fast inner loop that catches the eighty percent of regressions that are the role’s own fault, so that the slow outer loop has less to catch.
Finally, if the role is ten lines and changes twice a year, the scenario will cost more to maintain than it returns. Start with the roles that change often and touch things that hurt when they break.
For the underlying mechanics of playbooks and task structure, Ansible playbook basics covers the ground this article assumes. Molecule’s own documentation is the reference for scenario configuration options.
If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.