TExcelTAD
Home › Configuration Management: Ansible › Testing Roles with Molecule

Testing Roles with Molecule

ansible-lint reads your code; Molecule runs it. For a role, a Molecule scenario describes a test: create a test machine, apply the role (converge), apply it again and expect no changes (idempotence), then check the result (verify), and finally destroy the machine.

Drivers

The driver decides what the test machine is:

Driver Test instance
default (delegated) whatever you provide: an existing host, a VM your own create.yml starts, or localhost
molecule-plugins[docker], [podman] a container per platform (fast; systemd needs extra setup)
molecule-plugins[vagrant] a VM
cloud drivers (EC2, Azure, GCE) a cloud VM

This course's sandbox has no Docker or VMs, so the scenario here uses the default driver without managed instances and runs the role against localhost. The test sequence, idempotence check and verify playbook are exactly the same with containers; only create/destroy differ.

The layout

text
roles/motd/
├── defaults/main.yml
├── tasks/main.yml
└── molecule/
    └── default/              # the scenario's name
        ├── molecule.yml      # driver, platforms, test sequence
        ├── inventory.yml     # (delegated driver) how to reach the instance
        ├── converge.yml      # applies the role
        └── verify.yml        # checks the result

molecule init scenario writes a commented starting point; the files below are trimmed to what the test needs.

A complete test run

bash · try it yourself
mkdir -p roles/motd/{tasks,defaults,molecule/default} && cd roles/motd
cat > defaults/main.yml <<'YML'
---
motd_path: /home/learner/motd.txt
motd_team: platform
YML
cat > tasks/main.yml <<'YML'
---
- name: Write the message of the day
  ansible.builtin.copy:
    dest: "{{ motd_path }}"
    content: "Managed by the {{ motd_team }} team.\n"
    mode: "0644"
YML
cat > molecule/default/molecule.yml <<'YML'
---
driver:
  name: default
  options:
    managed: false            # Molecule doesn't create or destroy instances
platforms:
  - name: instance
ansible:
  env:
    ANSIBLE_ROLES_PATH: ${MOLECULE_PROJECT_DIRECTORY}/..
  cfg:
    defaults:
      interpreter_python: auto_silent
  executor:
    args:
      ansible_playbook:
        - --inventory=${MOLECULE_SCENARIO_DIRECTORY}/inventory.yml
dependency:
  name: galaxy
  enabled: false              # nothing to install (and no network here)
scenario:
  test_sequence:
    - syntax
    - converge
    - idempotence
    - verify
YML
cat > molecule/default/inventory.yml <<'YML'
---
all:
  hosts:
    instance:
      ansible_connection: local
YML
cat > molecule/default/converge.yml <<'YML'
---
- name: Converge
  hosts: all
  gather_facts: false
  roles:
    - role: motd
      vars:
        motd_team: data
YML
cat > molecule/default/verify.yml <<'YML'
---
- name: Verify
  hosts: all
  gather_facts: false
  tasks:
    - name: Read the motd
      ansible.builtin.slurp:
        src: /home/learner/motd.txt
      register: motd

    - name: The motd names the team
      ansible.builtin.assert:
        that: (motd.content | b64decode) == "Managed by the data team.\n"
YML
PY_COLORS=0 molecule test
INFO     [default > discovery] scenario test matrix: syntax, converge, idempotence, verify
INFO     [default > prerun] Performing prerun with role_name_check=0...
INFO     [default > syntax] Executing

playbook: /home/learner/roles/motd/molecule/default/converge.yml
INFO     [default > syntax] Executed: Successful
INFO     [default > converge] Executing

PLAY [Converge] ****************************************************************

TASK [motd : Write the message of the day] *************************************
changed: [instance]

PLAY RECAP *********************************************************************
instance                   : ok=1    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

INFO     [default > converge] Executed: Successful
INFO     [default > idempotence] Executing

PLAY [Converge] ****************************************************************

TASK [motd : Write the message of the day] *************************************
ok: [instance]

PLAY RECAP *********************************************************************
instance                   : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

INFO     [default > idempotence] Executed: Successful
INFO     [default > verify] Executing

PLAY [Verify] ******************************************************************

TASK [Read the motd] ***********************************************************
ok: [instance]

TASK [The motd names the team] *************************************************
ok: [instance] => {
    "changed": false,
    "msg": "All assertions passed"
}

PLAY RECAP *********************************************************************
instance                   : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

INFO     [default > verify] Executed: Successful
INFO     Molecule executed 1 scenario (1 successful)

DETAILS
default > syntax: Executed: Successful
default > converge: Executed: Successful
default > idempotence: Executed: Successful
default > verify: Executed: Successful

SCENARIO RECAP
default                   : actions=4  successful=4  disabled=0  skipped=0  missing=0  failed=0

The stages, in order:

  1. syntax: ansible-playbook --syntax-check on converge.yml.
  2. converge: the role runs and makes changes (changed=1).
  3. idempotence: the role runs again; Molecule fails the test if any task reports changed. This catches the commands without changed_when, the state: latest and the templates with timestamps that slip through review.
  4. verify: verify.yml checks the result with asserts (Molecule also supports Testinfra, Python tests with host.file(...)).

PY_COLORS=0 keeps Molecule's own log lines plain, like NO_COLOR elsewhere.

A failing idempotence check

Change the task to a command without changed_when, and the idempotence stage fails:

bash · try it yourself
mkdir -p roles/stamp/{tasks,molecule/default} && cd roles/stamp
cat > tasks/main.yml <<'YML'
---
- name: Write a build stamp
  ansible.builtin.command: sh -c 'echo built > /home/learner/stamp.txt'
YML
cat > molecule/default/molecule.yml <<'YML'
---
driver:
  name: default
  options:
    managed: false
platforms:
  - name: instance
ansible:
  env:
    ANSIBLE_ROLES_PATH: ${MOLECULE_PROJECT_DIRECTORY}/..
  cfg:
    defaults:
      interpreter_python: auto_silent
  executor:
    args:
      ansible_playbook:
        - --inventory=${MOLECULE_SCENARIO_DIRECTORY}/inventory.yml
dependency:
  name: galaxy
  enabled: false
scenario:
  test_sequence: [converge, idempotence]
YML
printf 'all:\n  hosts:\n    instance:\n      ansible_connection: local\n' > molecule/default/inventory.yml
printf -- '- name: Converge\n  hosts: all\n  gather_facts: false\n  roles: [stamp]\n' > molecule/default/converge.yml
PY_COLORS=0 molecule test 2>&1 | grep -E '^(CRITICAL|\*  =>)'
echo "exit code: ${PIPESTATUS[0]}"
CRITICAL Idempotence test failed because of the following tasks:
*  => stamp : Write a build stamp
*  => stamp : Write a build stamp
exit code: 1

Fix it with creates: /home/learner/stamp.txt (or changed_when), and the test passes.

Day-to-day commands

Command Does
molecule test the full sequence, then cleanup; what CI runs
molecule converge create (if needed) + converge; leaves the instance for inspection
molecule idempotence, molecule verify single stages against the existing instance
molecule login a shell in the instance (container and VM drivers)
molecule destroy remove the instance
molecule test -s upgrade run another scenario (e.g. upgrade from the previous role version)

With the Docker driver, platforms: lists images (ubuntu:24.04, rockylinux:9), so one molecule test checks the role on several distributions. In CI that is a job per platform; on a laptop it needs Docker or Podman.

Test yourself

What does Molecule's idempotence stage check?

  1. That the role is linted
  2. That a second converge reports no changed tasks
  3. That the instance is destroyed
  4. That verify.yml exists

Which driver lets you test against an existing host or localhost?

  1. docker
  2. the default (delegated) driver
  3. vagrant
  4. ec2

Where do the result checks of a scenario usually live?

  1. converge.yml
  2. verify.yml
  3. molecule.yml
  4. defaults/main.yml