Stage 4 · Provision
Testing, AWX & CI/CD
Testing Roles With Molecule
Scenarios, Docker drivers, converge, and idempotence tests.
What Is Molecule?
Molecule is a testing framework for Ansible roles. It creates clean test environments (using Docker, Podman, or Vagrant), runs your role, verifies the result, and tears down the environment. Every role should have Molecule tests.
Molecule Setup
# Install Molecule with Docker driver
pip install molecule molecule-plugins[docker]
# Verify installation
molecule --version
# Initialize Molecule in a role
cd roles/my-role
molecule init scenarioMolecule creates a molecule/ directory with scenario files. The default scenario uses Docker as the test driver.
---
dependency:
name: galaxy
driver:
name: docker
platforms:
- name: instance
image: quay.io/centos/centos:stream9
pre_build_image: true
privileged: true
provisioner:
name: ansible
verifier:
name: ansible
lint: |-
ansible-lintmolecule.yml defines the test platform, provisioner, and verifier. Docker is the fastest option for CI.
Molecule Scenarios
# molecule/default/molecule.yml - default scenario
# molecule/centos/molecule.yml - CentOS-specific
# molecule/ubuntu/molecule.yml - Ubuntu-specific
# Run specific scenario
molecule test -s centos
# List all scenarios
molecule listMultiple scenarios test your role across different operating systems and configurations. This catches OS-specific issues early.
Converge and Test
---
- name: Converge
hosts: all
become: yes
roles:
- role: my-role
vars:
my_role_var: "test-value"converge.yml is the playbook that applies your role to the test container. It runs the role and verifies the result.
---
- name: Verify
hosts: all
become: yes
tasks:
- name: Check package is installed
ansible.builtin.package:
name: nginx
check_mode: yes
register: result
failed_when: result.changed
- name: Check service is running
ansible.builtin.command: systemctl is-active nginx
register: result
changed_when: false
- name: Check port is listening
ansible.builtin.wait_for:
port: 80
timeout: 5verify.yml runs assertions after converge. If any task fails, the Molecule test fails.
Idempotence Testing
# Run full test suite (create, converge, verify, idempotence, destroy)
molecule test
# Run only idempotence test
molecule idempotence
# Run converge without destroying
molecule converge
# Clean up
molecule destroyThe idempotence test runs converge twice. If the second run reports any changes, the test fails. This proves your role is truly idempotent.
If your role is not idempotent, running it twice produces different results. This is a bug. The idempotence test catches this automatically.
Run molecule test in CI on every pull request. This ensures your role works across platforms before merging. Use Docker for fast, isolated tests.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.