Skip to content

Molecule

"Molecule is designed to aid in the development and testing of Ansible roles." - https://molecule.readthedocs.io

Examples

Initialize a new role to be tested in docker

molecule init role ansible-role-whatever --driver-name docker

The above command creates the following directory structure with boilerplate filled in, similar to what you'd expect from cookiecutter.

ansible-role-whatever/.travis.yml
ansible-role-whatever/.yamllint
ansible-role-whatever/README.md
ansible-role-whatever/defaults/main.yml
ansible-role-whatever/handlers/main.yml
ansible-role-whatever/meta/main.yml
ansible-role-whatever/molecule/default/INSTALL.rst
ansible-role-whatever/molecule/default/converge.yml
ansible-role-whatever/molecule/default/molecule.yml
ansible-role-whatever/molecule/default/verify.yml
ansible-role-whatever/tasks/main.yml
ansible-role-whatever/tests/inventory
ansible-role-whatever/tests/test.yml
ansible-role-whatever/vars/main.yml

Profile a molecule run

Profiling molecule itself

This profiles the molecule run, but not everything is shown due to not everything being python native.

$ python3 -m cProfile -o ansible-run.cprofile $(which molecule) test
...normal molecule output scrolls by...

$ python3 -m pstats ansible-run.cprofile
Welcome to the profile statistics browser.
ansible-run.cprofile% sort cumulative
ansible-run.cprofile% stats 20
Mon Jan 13 08:56:45 2020    ansible-run.cprofile
         1782927 function calls (1731081 primitive calls) in 145.057 seconds
   Ordered by: cumulative time
   List reduced from 6303 to 20 due to restriction <20>
   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
   1247/1    0.005    0.000  145.060  145.060 {built-in method builtins.exec}
        1    0.000    0.000  145.060  145.060 /Users/daniel.hoherd/Library/Python/3.7/bin/molecule:3(<module>)
        1    0.000    0.000  144.267  144.267 /Users/daniel.hoherd/Library/Python/3.7/lib/python/site-packages/click/core.py:762(__call__)
...

Profiling testinfra runs

Install pytest-profiling, which adds the --profile flag needed in the next step

pip3 instlal --user pytest-profiling

Then set up your molecule/scenario/molecule.yml file with the following env contents:

verifier:
  name: testinfra
  env:
    PYTEST_ADDOPTS: '--profile'

See Also