How to test Ansible code with Molecule

Molecule is the official testing framework for Ansible roles. It provides a streamlined way to create a virtualized environment to test the syntax and functionality of a role.

Molecule encourages an approach that results in consistently developed roles that are well-written, easily understood and maintained.

Molecule uses Ansible playbooks to execute roles and tests. It can detect errors such as syntax errors; structural problems like the use of undefined variables, etc.

Molecule can be used with Docker or Podman containers.

Here are some steps to use Molecule to test Ansible code:

  • Install Molecule using pip: pip install molecule
  • Create a new role using ansible-galaxy: ansible-galaxy init my_role
  • Change directory into our new role: cd my_role
  • Initialize Molecule in our role directory: molecule init scenario --scenario-name default -r my_role -d podman
  • Write our tests in the molecule/default/tests directory
  • Test our role using Molecule: molecule test

Molecule provides support for testing with multiple instances, operating systems and distributions, virtualization providers, test frameworks and testing scenarios.

This makes it an ideal tool for testing Ansible code.

Leave a comment