Seite wählen

NETWAYS Blog

Ansible – Testing roles with Molecule

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.

molecule/default/molecule.yml


---
dependency:
  name: galaxy
  options:
    requirements-file: collections.yml
driver:
  name: vagrant
platforms:
  - name: instance
    box: bento/centos-7
provisioner:
  name: ansible
verifier:
  name: testinfra
  options:
    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.

molecule/default/converge.yml


---
- name: Converge
  hosts: all
  become: true
  tasks:
    - name: "Include thilo.my_config"
      include_role:
        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
or 
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
Manager Consulting

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.

Minimale Rechte und persönliche Accounts zur Administration

Icinga 2
Nachdem in unserer letzten „Icinga 2“-Schulung die Diskussion aufkam wie man Icinga 2 am besten mit minimalen Rechten konfiguriert und administriert, will ich mich dieser Thematik mal annehmen. Dies wird zwar anhand des Beispiels Icinga 2 auf CentOS 7 sein, aber lässt sich so auf jeden Dienst anwenden, der in Konfigurationsdateien verwaltet wird.
Ausgangsbasis
Die Ausgangsbasis stellen immer die Rechte dar, die durch das Package bei der Installation vorgegeben werden. Diese sollen unverändert bleiben, da sie sonst bei einem Update wieder auf den Standard des Packages zurückgesetzt werden. Als zweites gehen wir mal davon aus, dass eine Anmeldung als unpriviligierter Benutzer mit einem persönlichen Account möglich ist, wobei egal ist ob dieser lokal angelegt ist oder aus einem zentralen Verzeichnisdienst kommt, und dass dieser zur Administration genutzt werden soll.
Bei Icinga 2 sehen die Rechte nach der Installation folgendermaßen aus:

  • Auf dem Hauptverzeichnis /etc/icinga2 hat root alle Rechte, die Gruppe icinga darf lesen und browsen, alle anderen haben keine Rechte.
  • Auf die Dateien und Unterverzeichnisse hat der Benutzer icinga alle Rechte, die Gruppe icinga darf lesen und Verzeichnisse browsen, alle anderen haben keine Rechte.
  • Die Ausnahme bildet die Datei /etc/icinga2/init.conf, bei der die Benutzerrechte auf root liegen, aber auch nicht editiert werden sollte.

Zusätzlich zu den Dateirechten brauchen wir zur Administration Befehle wie systemctl reload icinga2.service um Icinga 2 neuzustarten oder auch icinga2 daemon -C zum Validieren der Konfiguration. Die Systemkommandos können nur als root ausgeführt werden, die Icinga-Kommandos als root oder icinga. Der Benutzer icinga ist allerdings als Benutzer gedacht unter dem der Dienst läuft und hat daher keine Benutzerumgebung, Kommandos können mit sudo aber trotzdem mit seinen Rechten ausgeführt werden.
Ein unpriviligierter Account kann nun noch nicht mal die Konfiguration lesen oder auch nur durch die Verzeichnisse navigieren, den Dienst nicht steuern oder Icinga-Kommandos absetzen. Dies können wir auf zwei Arten lösen. Methode 1 sind Gruppenrechte, Methode 2 ACLs, beides angereichert um eine Prise sudo um Kommandos unter anderen Rechten auszuführen.
mehr lesen…

Dirk Götz
Dirk Götz
Principal Consultant

Dirk ist Red Hat Spezialist und arbeitet bei NETWAYS im Bereich Consulting für Icinga, Puppet, Ansible, Foreman und andere Systems-Management-Lösungen. Früher war er bei einem Träger der gesetzlichen Rentenversicherung als Senior Administrator beschäftigt und auch für die Ausbildung der Azubis verantwortlich wie nun bei NETWAYS.