Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Using Molecule for Testing and Validation

Introduction

Molecule is a robust testing framework designed for Ansible roles. It allows developers and DevOps engineers to test their infrastructure code in an isolated environment, ensuring that changes do not break existing configurations.

Installation

Before you can use Molecule, you need to have Python and Ansible installed. Follow these steps to install Molecule:

Install Molecule using pip:

pip install molecule

Verify the installation:

molecule --version

Setting Up a New Role

To set up a new Ansible role with Molecule, use the following command:

molecule init role <role_name>

This command will generate a directory structure with all the necessary configuration files for Molecule.

Directory Structure

Once you initialize a role, you will see a directory structure similar to this:

|-- molecule
|   |-- default
|       |-- converge.yml
|       |-- molecule.yml
|       |-- verify.yml
|-- tasks
|-- handlers
|-- meta
|-- README.md
|-- tests
                

Each of these files and directories has a specific purpose. For example, converge.yml is used to apply the role, and verify.yml is used to run tests.

Configuring Molecule

The molecule.yml file contains the configuration for Molecule. You can define the driver, platform, and provisioner in this file. Here is an example configuration:

driver:
  name: docker

platforms:
  - name: instance
    image: centos:7
    privileged: true

provisioner:
  name: ansible
  log: true
                

In this example, we are using Docker as the driver and CentOS 7 as the platform.

Running Molecule

To run Molecule and test your role, use the following command:

molecule test

This command will go through the entire lifecycle of creating instances, applying the role, and running tests.

Writing Test Cases

Test cases are written in the verify.yml file using Ansible tasks. Here is an example:

- name: Verify httpd is installed
  command: rpm -qa | grep httpd
  register: result
  failed_when: result.rc != 0
                

This task checks if the httpd package is installed on the instance.

Destroying Instances

After testing, you can destroy the instances created by Molecule using the following command:

molecule destroy

This helps in cleaning up resources and ensuring that you do not incur unnecessary costs.

Conclusion

Molecule is a powerful tool for testing Ansible roles, providing a structured way to validate your infrastructure code. By following this tutorial, you should be able to set up, configure, and run Molecule to ensure the reliability of your Ansible roles.