molecule

Overview

Tool for setting testing ansible roles, replacement for manually creating test instances with vagrant/scripts.

Tasks:

Reasons to use:

Example

Testing a role that configures a VPN, e.g. Wireguard. This role sets up Wireguard on multiple targets and configures a connection between them.

First, in your role's direcory create a new scenario with molecule init scenario -d docker default. Notice -d docker to set docker as driver.

Then, in molecule/default/molecule.yaml configure your instances:

---
driver:
  name: docker
platforms:
  - name: instance1
    image: travisci/ubuntu-systemd:22.04
    privileged: True
    volume_mounts:
      - "/sys/fs/cgroup:/sys/fs/cgroup:rw"
    command: "/lib/systemd/systemd"
    networks:
      - name: my-role-molecule
    groups:
      - wireguard
  - name: instance2
    image: travisci/ubuntu-systemd:22.04
    privileged: True
    volume_mounts:
      - "/sys/fs/cgroup:/sys/fs/cgroup:rw"
    command: "/lib/systemd/systemd"
    networks:
      - name: my-role-molecule
    groups:
      - wireguard
provisioner:
  name: ansible
  inventory:
    group_vars:
      wireguard:
        wireguard_extra_config: |
          some_extra_config
    host_vars:
      instance1:
        wireguard_my_addr: 10.100.99.1/24
      instance2:
        wireguard_my_addr: 10.100.99.2/24

Important parts:

Next, molecule/default/converge.yml is the playbook that gets executed to test your role. Most of the time you'll only need to add this:

gather_facts: true
roles:
  - my-role

Finally, run your converge playbook with molecule test, which will setup your targets, run your role and then destroy the targets. As written above, molecule is an environment manager:

Notes

I'm either bad at googling or documentation is really sparce. I've been mostly trying random things until it works.

Molecule packaging in nix is kind of weird, simplest way to do it is including this in your shell's packages:

[
  ansible
  (python3.withPackages (ps: [
    ps.molecule
    ps.molecule-plugins
    ps.docker
  ]))
]