Seite wählen

Ansible – Testing roles with Molecule

von | Sep 15, 2022 | Linux, Automation, DevOps, Python, Ansible

Ansible is a widely used and a powerful open-source configuration and deployment management tool. It can be used for simple repetitive daily tasks or complex application deployments, therefore Ansible is able to cover mostly any situation.

If used in complex or heterogene environments it is necessary to test the code to reduce time to fix code in production. To test Ansible code it is suggested to use Molecule.

Molecule is a useful tool to run automated tests on Ansible roles or collections. It helps with unit tests to ensure properly working code on different systems. Whether using the role internally or provide it to the public, it is useful to test many cases your role can be used. In addition Molecule is easily integrated into known CI/CD tools, like Github Actions or Gitlab CI/CD.

In this short introduction I’ll try get your first Molecule tests configured and running!

Please make sure you installed Molecule beforehand. On most distributions it’s easily installed via PIP.
The fastest and most common way to test roles would be in container. Due to a version problem with systemd currently it’s not possible to start services over systemd in containers. For this reason you can easily start with a vagrant instance and later migrate to docker or podman easily.

pip install molecule molecule-vagrant

If you have a role you can change into the role directory and create a default scenario.

cd ~/Documents/netways/git/thilo.my_config/
molecule init scenario -r thilo.my_config default
INFO     Initializing new scenario default...
INFO     Initialized scenario in /Users/thilo/Documents/netways/git/thilo.my_config/molecule/default successfully.

Below the molecule folder all scenarios are listed. Edit the default/molecule.yml to add the vagrant options.

Add a dependency file with your collections as with newer Ansible versions only the core is available. If needed you can add sudo privileges to your tests.


  name: galaxy
    requirements-file: collections.yml
  name: vagrant
  - name: instance
    box: bento/centos-7
  name: ansible
  name: testinfra
    sudo: true

The converge.yml is basically the playbook to run on your instance. In the playbook you define which variables should be used or if some pre-tasks should be run.


- name: Converge
  hosts: all
  become: true
    - name: "Include thilo.my_config"
        name: "thilo.my_config"

Now you can run your playbook with molecule. If you want to deploy and not delete your instance use converge. Otherwise you can use test, then the instance will be created, tested and destroyed afterwards.

python3 -m molecule converge -s default
python3 -m molecule test -s default

Finally we can define some tests, the right tool is testinfra. Testinfra provides different modules to gather informations and check them if they have specific attributes.

Your scenario creates a tests folder with the following file: molecule/default/tests/test_default.py

In this example I’ll test the resources my role should create.

"""Role testing files using testinfra."""

def test_user(host):
    """Validate created user"""
    u = host.user("thilo")

    assert u.exists

def test_authorized_keys(host):
    """Validate pub key deployment"""
    f = host.file("/home/thilo/.ssh/authorized_keys")

    assert f.exists
    assert f.content_string == "ssh-rsa AAAA[...] \n"

And if we already converged our instance, we can verify these definitions against our deployment.

python3 -m molecule verify
INFO     default scenario test matrix: verify
INFO     Performing prerun with role_name_check=0...
INFO     Running default > verify
INFO     Executing Testinfra tests found in /Users/thilo/Documents/netways/git/thilo.my_config/molecule/default/tests/...
============================= test session starts ==============================
platform darwin -- Python 3.9.12, pytest-6.2.5, py-1.11.0, pluggy-0.13.1
rootdir: /
plugins: testinfra-6.4.0
collected 2 items

molecule/default/tests/test_default.py ..                                [100%]

============================== 2 passed in 1.79s ===============================
INFO     Verifier completed successfully.

With those easy steps you can easily test your roles for any scenario and your deployments can run without any hassle or at least you will be more relaxed during it 😉

Check out our Blog for more awesome posts and if you need help with Ansible send us a message or sign up for one of our trainings!

Thilo Wening
Thilo Wening
Senior Consultant

Thilo hat bei NETWAYS mit der Ausbildung zum Fachinformatiker, Schwerpunkt Systemadministration begonnen und unterstützt nun nach erfolgreich bestandener Prüfung tatkräftig die Kollegen im Consulting. In seiner Freizeit ist er athletisch in der Senkrechten unterwegs und stählt seine Muskeln beim Bouldern. Als richtiger Profi macht er das natürlich am liebsten in der Natur und geht nur noch in Ausnahmefällen in die Kletterhalle.
Mehr Beiträge zum Thema Linux | Automation | DevOps | Python | Ansible

Kleine Weihnachtspyramide mit Raspberry Pi

Noch einmal schlafen und dann ist Weihnachten. Passend dazu haben wir von NETWAYS ein kleines Experiment zum selber Nachbauen vorbereitet. Es handelt sich um eine kleine Weihnachtspyramide, die sich mithilfe von Python Code und ein paar Bauteilen ein wenig bewegt und...

Automate Icinga for Windows with Ansible

This article will cover how to automate the monitoring of your windows infrastructure with Ansible and Icinga for Windows. For that, I developed a new Ansible role which you can find here: https://github.com/DanOPT/ansible-role-ifw The role will allow you to manage...

Ansible Continuous Deployment without AWX/Tower/AAP

Why Ansible? Ansible is a configuration management tool to automate tasks in your IT infrastructure. It offers a rather low barrier of entry, when compared to other tools. A local Ansible installation (i.e. on your machine) with SSH access to the infrastructure you...

Leap(p) to Red Hat Enterprise Linux 9

Ich muss mich direkt für das Wortspiel im Titel entschuldigen, aber es lag so nahe als ich mich für das Thema entschieden hatte, denn ich möchte einen neuen Blick auf Leapp werfen mit dem Upgrades von Red Hat Enterprise Linux (RHEL) durchgeführt werden können. Der...