Minimal Molecule Testing, how much code do you really need?

Overview

Molecule is the default testing environment for ansible, unfortunately it requires a lot of boiler plate just to make it work (all I want it to do is just run my test and tell me if it worked!) This page is my attempt to strip down the amount of boiler plate code required to do testing with Molecule and do everything as DRY as possible.

The Setup

This setup assumes you are sane person using a mono-repo that contains all your roles. If you are breaking all your roles out into separate repos you've already set yourself up for a life of pain and misery; enjoy!

Directory layout

This is what your directory layout should look like. The roles_dir is the directory that contains all of your ansible roles. The my_role is the sample role we will be adding testing to.

roles_dir
  molecule_base
    default.yml
  my_role
    molecule
      default
        converge.yml
        verify.yml
        molecule.yml

The files

molecule_base/default.yml

This is the default config for molecule. In this example I'll be setting docker up to use docker with a cent7 image to test the role:

---
dependency:
  name: galaxy
driver:
  name: docker
platforms:
  - name: cent7
    image: docker.io/pycontribs/centos:7
    pre_build_image: true
provisioner:
  name: ansible
verifier:
  name: ansible
lint: |
  set -e
  yamllint .
  ansible-lint .

my_role/molecule/default/converge.yml

More boiler plate code required to run molecule, this is just telling molecule to run the role of the directory we are in.

---
- name: Converge
  hosts: all
  roles:
   - role: "{{ lookup('env', 'MOLECULE_PROJECT_DIRECTORY') | basename }}"

my_role/molecule/default/verify.yml

This file contains all the testing you want to do after you run your role. Because this file is ansible code which isn't very well suited for "testing", it can get very long and complicated to do simple things (like check if a file exists)

---
- name: Verify
  hosts: all
  gather_facts: false
  tasks:

  - name: include defaults
    include_vars:
      file: ../../defaults/main.yml

  - name: stat file
    stat:
      path: "{{ file_name }}"
    register: file_exist_check

  - name:
    assert:
      that:
        - file_exist_check.stat.exists == True
      success_msg: "{{ file_name }} exists pass"
      fail_msg: "{{ file_name }} does not exist fail"

my_role/molecule/default/molecule.yml

this file just needs to exist and be blank (yay more boiler plate)

Running Molecule

Now that you have your files setup, it's time to run molecule.

Other fun molecule commands

Note that m test will delete the docker instance at the end of the run, so if you want to login and poke around, you'll need to manually stand the instance up as shown in the command list above.



Back