Molecule (Ansible Testing Framework)

26.4.0 · active · verified Sat Apr 11

Molecule is an Ansible testing framework designed for developing and testing Ansible collections, playbooks, and roles. It provides support for testing with multiple instances, operating systems, distributions, virtualization providers, test frameworks, and testing scenarios. Molecule encourages an approach that results in consistently developed Ansible content that is well-written, easily understood, and maintained. The current version is 26.4.0, and releases generally align with Ansible development, with major versions introducing significant changes.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates the standard command-line workflow for Molecule, creating a minimal Ansible role, initializing a default Molecule scenario with a Docker driver, and running the full test lifecycle. It includes a basic 'verify.yml' example for illustration. The primary interaction with Molecule is via its command-line interface, even when invoked from Python.

import os
import subprocess

# Create a dummy Ansible role directory
role_name = "my_test_role"
if not os.path.exists(role_name):
    os.makedirs(os.path.join(role_name, "tasks"))
    with open(os.path.join(role_name, "tasks", "main.yml"), "w") as f:
        f.write("---\n- name: Example task\n  ansible.builtin.debug:\n    msg: 'Hello from Molecule!'")

# Change into the role directory
os.chdir(role_name)

# Initialize a Molecule scenario (using the default Docker driver)
# This will create the molecule/default directory and its files
print("Initializing Molecule scenario...")
subprocess.run(["molecule", "init", "scenario", "--driver-name", "docker", "--scenario-name", "default"], check=True)

# Define a simple verify.yml (optional, but good practice)
verify_yml_content = '''---
- name: Verify role execution
  hosts: all
  gather_facts: false
  tasks:
    - name: Check if message was in logs (example)
      ansible.builtin.command: cat /var/log/ansible_messages.log # Replace with actual verification
      changed_when: false
      failed_when: false
      register: log_output
    - name: Assert message content
      ansible.builtin.assert:
        that:
          - "'Hello from Molecule!' in log_output.stdout"
        fail_msg: "Expected message not found in logs."
'''
with open(os.path.join("molecule", "default", "verify.yml"), "w") as f:
    f.write(verify_yml_content)

# Run the full Molecule test sequence
print("Running full Molecule test sequence...")
try:
    subprocess.run(["molecule", "test"], check=True)
    print("Molecule test completed successfully.")
except subprocess.CalledProcessError as e:
    print(f"Molecule test failed: {e}")
finally:
    # Clean up (optional, but good for quickstart)
    print("Cleaning up Molecule resources...")
    subprocess.run(["molecule", "destroy"], check=False) # destroy if it failed earlier
    os.chdir("..")
    # Optionally remove the role directory: shutil.rmtree(role_name)

view raw JSON →