Ansible-lint + Molecule: lint and test roles
IaC · Ansible
Added 2026-10-29.
Problem
A role works on one server and breaks on another; a second run changes something again. Errors are found in production.
Solution
Two levels of checks:
- ansible-lint "checks playbooks for practices and behavior that could potentially be improved" — statically, before anything runs, with rule profiles from
mintoproduction. - Molecule is "an Ansible testing framework designed for developing and testing Ansible collections, playbooks, and roles". On a disposable test host it applies the role, applies it again (idempotence must give
changed=0) and verifies the result.
Example
The linter in pre-commit:
repos:
- repo: https://github.com/ansible/ansible-lint
rev: v26.10.1
hooks:
- id: ansible-lint
ansible-lint --profile basic # start with basic, raise the level gradually
Molecule — the sequence in molecule/default/molecule.yml:
scenario:
test_sequence:
- dependency
- destroy
- create
- converge
- idempotence
- verify
- destroy
molecule/default/verify.yml — verify the result, not just the absence of errors:
- name: Verify
hosts: all
tasks:
- name: Nginx config is valid
ansible.builtin.command: nginx -t
changed_when: false
molecule test
Creating and destroying the test container is described in create.yml and destroy.yml; the Molecule docs show an example with the containers.podman collection.
When to use
For every role applied to more than one server.
Source
How to apply it yourself
- Enable
ansible-lint --profile basicon one role and fix the findings. - Add a Molecule scenario with idempotence and verify.
- Make sure the second run gives
changed=0. - Mark it "Studied" once both steps run in CI.