Ansible Molecule: Testing and Developing Ansible Roles
Ansible Molecule is a tool designed to aid in the development and testing of Ansible roles. It allows you to write infrastructure-as-code in a test-driven development (TDD) style, ensuring that your Ansible roles are robust, reliable, and reusable. This document provides a comprehensive guide to using Ansible Molecule, covering installation, basic usage, testing strategies, and integration with CI/CD pipelines.
What is Ansible Molecule?
Molecule provides an abstraction layer to manage the complexity of testing Ansible roles, by utilizing containerization (e.g., Docker, Podman), virtual machines (e.g., Vagrant, VirtualBox), or cloud environments for testing. It supports various testing scenarios, including:
- Idempotency testing: Verifying that running a role multiple times has the same result.
- Syntax checking: Ensuring that Ansible Playbooks and YAML files are syntactically correct.
- Linting: Applying style guidelines to Ansible code for consistency.
- Integration testing: Testing the role's functionality after it has been applied.
Use Cases for Ansible Molecule
- Developing Reusable Roles: Molecule encourages the creation of well-structured and documented roles that can be easily reused across different projects and environments.
- Ensuring Role Quality: By implementing automated tests, Molecule helps to maintain the quality and reliability of Ansible roles.
- Automating Testing in CI/CD: Integrating Molecule into your CI/CD pipeline allows you to automatically test roles whenever changes are made, ensuring that the infrastructure remains stable.
- Validating Infrastructure Changes: Use Molecule to test changes to existing infrastructure configurations before deploying them to production.
- Standardizing Role Development: Provides a consistent methodology for developing and testing Ansible roles across a team or organization.
Local Installation
-
Prerequisites:
- Python: Molecule requires Python 3.6 or later.
- Pip: Python package installer. Usually comes with Python installations.
- Ansible: Molecule relies on Ansible to execute tasks within the test environments. Install Ansible using
pip install ansible
. - Docker (Recommended): Docker or other containerization tools (Podman) is recommended, as it provides an isolated and reproducible environment for testing. Install Docker Desktop or Docker Engine according to your operating system. Ensure Docker is running.
- Community.docker: Install the
community.docker
collection for Ansible.ansible-galaxy collection install community.docker
-
Install Molecule using Pip:
Open a terminal and run the following command:
pip install molecule
It's recommended to use a virtual environment to isolate the Molecule installation from other Python projects:
python3 -m venv .venv
source .venv/bin/activate # On Linux/macOS
# .venv\Scripts\activate On Windows
pip install molecule -
Verify the Installation:
To verify that Molecule is installed correctly, run the following command:
molecule --version
This should display the installed version of Molecule.
Basic Usage
-
Create a New Role:
Use the
ansible-galaxy
command to create a new Ansible role:ansible-galaxy init my_role
-
Initialize Molecule:
Navigate to the newly created role directory and initialize Molecule:
cd my_role
molecule init scenario --driver dockermolecule init scenario
creates a basic Molecule scenario.--driver docker
specifies that Docker will be used as the test environment. You can choose other drivers like Vagrant or Podman too.
-
Explore the Molecule Directory Structure:
The
molecule
command creates a directory structure within your role:my_role/
├── .git/
├── .gitignore
├── defaults/
├── files/
├── handlers/
├── meta/
├── molecule/
│ └── default/ # This is your default scenario
│ ├── converge.yml # Playbook to converge your role. This *applies* the role
│ ├── molecule.yml # Molecule configuration file
│ ├── prepare.yml # Playbook to prepare the test environment.
│ └── verify.yml # Playbook to verify the role's configuration
├── README.md
├── tasks/
├── templates/
└── vars/ -
Configure
molecule.yml
:This file is the heart of your Molecule configuration. It defines the scenario you want to test, the driver to use, and other settings. Here's a basic example:
---
dependency:
name: galaxy
driver:
name: docker
platforms:
- name: ubuntu-latest
image: "ubuntu:latest"
pre_build_image: false
provisioner:
name: ansible
verifier:
name: ansibledependency
: Defines how to manage role dependencies (e.g., usingansible-galaxy
).driver
: Specifies the infrastructure driver (e.g.,docker
,vagrant
).platforms
: Defines the target platforms (e.g., operating systems) where the role will be tested.provisioner
: Specifies the Ansible provisioner.verifier
: Specifies the Ansible verifier used to test the state after provisioning.
-
Write Tests in
verify.yml
:The
verify.yml
file contains the tests that will be executed to verify that the role has been successfully applied. Use Ansible'sassert
module to check for expected outcomes.Example:
---
- name: Verify that nginx is installed
assert:
that:
- "'nginx' in ansible_facts.packages"
msg: "Nginx is not installed"
- name: Verify that nginx is running
service:
name: nginx
state: started -
Run Molecule:
Run Molecule from within the role directory:
molecule test
This command will execute the entire Molecule workflow:
- Dependency: Install role dependencies (if any).
- Create: Create the test environment (e.g., Docker container).
- Prepare: Prepare the environment for testing.
- Converge: Apply the Ansible role. This runs the main playbook for the role.
- Idempotence: Verify that the role is idempotent.
- Verify: Execute the tests defined in
verify.yml
. - Destroy: Destroy the test environment.
You can also run individual stages of the Molecule workflow using commands like:
molecule create
molecule converge
molecule verify
molecule destroy
Testing Strategies
- Idempotency Testing: Ensure that running a role multiple times does not change the system state. Molecule automatically tests for idempotency by running the
converge
playbook twice and checking for changes on the second run. - Unit Testing: While Molecule primarily focuses on integration testing, you can use it to simulate unit tests by mocking dependencies and focusing on specific aspects of the role's functionality.
- Property-Based Testing: Use tools like Hypothesis to generate test data and verify that the role behaves correctly under various conditions.
- Integration Testing: Use Molecule to test the role's interaction with other components of the infrastructure. This might involve testing network connectivity, database access, or API interactions.
- Regression Testing: Create a suite of tests that specifically address known issues or bugs. This helps to prevent regressions as the role evolves.