Infrastructure as code · Advanced · 22 min
Test Ansible roles with ansible-lint and Molecule
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · ansible-core 2.22.0 · ansible-lint 26.11.1 · Molecule 26.11.1
You will clean up a role until ansible-lint passes its production profile, then add a Molecule scenario that applies the role, proves a second run changes nothing and checks the result with a verify playbook.
On this page
A role that works once on your own server has proved very little. It may fail on the next host, report changed on every run so nobody trusts the recap, or leave files with whatever permissions the umask gave them. Two tools catch most of this before a role reaches a fleet. ansible-lint reads your YAML and flags patterns known to cause trouble. Molecule applies the role, applies it again to check that the second run changes nothing, and then runs a playbook you write to check the result.
You start with a small role, healthcheck, that installs a check script and its config file. It is written the way roles often are on a first pass, and it works. You lint it with the strictest profile, fix each finding and see why each fix matters. Then you add a Molecule scenario that tests the role against the machine you are on, so you need no Docker or Podman to follow along. The last step shows the container-based scenario most people run on a laptop or in CI.
Step 1 · Install the tools in a virtual environment
ansible-lint and Molecule both import ansible-core, so all three go in one Python virtual environment. Pin the versions so your output matches this page:
sudo apt update
sudo apt install -y python3-venv git
mkdir -p ~/ansible-test-demo
cd ~/ansible-test-demo
python3 -m venv .venv
source .venv/bin/activate
pip install --quiet "ansible-core==2.22.0" "ansible-lint==26.11.1" "molecule==26.11.1"ansible-core 2.22 needs Python 3.13 or newer; Ubuntu 26.04 ships a newer one. The environment takes about 60 MB on disk. On prepaid or metered data, install it once per machine and keep the folder: nothing is downloaded again until you change a pin. These packages get no updates from apt; upgrade them by changing the pins and running the same pip install line. Run source ~/ansible-test-demo/.venv/bin/activate in each new terminal before using the tools.
ansible-lint uses Git to find the root of your project and to skip ignored files, so make the folder a repository and ignore the environment:
git init -q
printf '.venv/\n' > .gitignoreCheck it worked
ansible --version | head -n 1
ansible-lint --version
molecule --versionThe first line starts with ansible [core 2.22.0]. ansible-lint prints ansible-lint 26.11.1 using ansible-core:2.22.0, and Molecule prints molecule 26.11.1 with ansible:2.22.0 and a default driver below it. Molecule may also print deprecation warnings about two ansible-core callback plugins; they come from ansible-core itself and do not affect this tutorial.
Step 2 · Write the role as a first draft
The role makes a folder, copies a shell script into it, writes a config file from a template and runs the script once so a broken install fails the play. Its install folder is a default, so a caller can change it:
mkdir -p roles/healthcheck/{defaults,files,meta,tasks,templates}
cat > roles/healthcheck/defaults/main.yml <<'YAML'
healthcheck_dir: /opt/healthcheck
healthcheck_url: http://127.0.0.1/
healthcheck_timeout: 5
YAML
cat > roles/healthcheck/files/check.sh <<'SH'
#!/bin/sh
# Reads the config next to this script and reports what it would check.
. "$(dirname "$0")/healthcheck.conf"
echo "healthcheck: url=$URL timeout=${TIMEOUT}s"
SH
cat > roles/healthcheck/templates/healthcheck.conf.j2 <<'J2'
# Managed by Ansible
URL={{ healthcheck_url }}
TIMEOUT={{ healthcheck_timeout }}
J2
cat > roles/healthcheck/meta/main.yml <<'YAML'
galaxy_info:
author: your-team
description: Installs a small health-check script and its config
license: MIT
min_ansible_version: "2.22"
platforms:
- name: Ubuntu
versions:
- all
dependencies: []
YAMLNow the tasks, written the quick way:
cat > roles/healthcheck/tasks/main.yml <<'YAML'
- name: create the install folder
file:
path: "{{ healthcheck_dir }}"
state: directory
- name: Copy the check script
copy:
src: check.sh
dest: "{{ healthcheck_dir }}/check.sh"
mode: "0755"
- name: write the config file
template:
src: healthcheck.conf.j2
dest: "{{ healthcheck_dir }}/healthcheck.conf"
- name: Run the check once
command: "{{ healthcheck_dir }}/check.sh"
register: healthcheck_result
YAMLEvery one of these tasks runs without error. That is the point: the problems ansible-lint finds are the kind a successful run hides.
Check it worked
find roles/healthcheck -type f | sortFive files are listed: defaults/main.yml, files/check.sh, meta/main.yml, tasks/main.yml and templates/healthcheck.conf.j2, each under roles/healthcheck/.
Step 3 · Lint the role with the production profile
ansible-lint groups its rules into profiles that grow stricter in this order: min, basic, moderate, safety, shared and production. production is the one to aim for with roles you run on real servers. Set it in a config file at the project root, so everyone who runs ansible-lint in this repository gets the same rules, and in CI too:
printf 'profile: production\n' > .ansible-lintRun the linter from the project root:
ansible-lintIt exits with code 2 and lists nine findings in four rules. Each line names the rule, the file and line, and the task:
fqcn[action-core]four times:file,copy,templateandcommandare short names. Write the fully qualified collection name,ansible.builtin.copy. A short name resolves through whatever collections are installed, so a collection that ships its owncopycould change what your task runs.name[casing]twice: task names should start with a capital letter. It sounds cosmetic, but names are what people read in the run output and what--start-at-taskmatches, so a consistent style pays off.risky-file-permissionstwice: the folder and the config file have nomode, so their permissions depend on the umask of whoever runs the play, and can differ between hosts.no-changed-whenonce: acommandtask always reportschanged, because Ansible cannot know what the command did. Every run then shows a change, and any handler it notifies fires every time.
The summary line reads Profile 'production' was required, but 'basic' profile passed., which tells you how far the role is from the target. Each finding links to its rule page in the documentation; read those when a rule's reason is not obvious.
Check it worked
You see the four rule names above and a Failed: 9 failure(s) line. Run echo $? straight after ansible-lint and it prints 2.
Step 4 · Fix each finding
Rewrite the tasks file with every fix in place:
cat > roles/healthcheck/tasks/main.yml <<'YAML'
- name: Create the install folder
ansible.builtin.file:
path: "{{ healthcheck_dir }}"
state: directory
mode: "0755"
- name: Copy the check script
ansible.builtin.copy:
src: check.sh
dest: "{{ healthcheck_dir }}/check.sh"
mode: "0755"
- name: Write the config file
ansible.builtin.template:
src: healthcheck.conf.j2
dest: "{{ healthcheck_dir }}/healthcheck.conf"
mode: "0644"
- name: Run the check once
ansible.builtin.command: "{{ healthcheck_dir }}/check.sh"
register: healthcheck_result
changed_when: false
YAMLchanged_when: false is right here because the script only reads its config and prints a line. Choose the fix by what the command does. A command that creates something gets creates: <path>, so Ansible skips it once the path exists. A command whose output tells you whether it changed something gets a changed_when test on that output, such as changed_when: "'updated' in result.stdout". Silencing the rule with # noqa: no-changed-when is a last resort, and deserves a comment saying why.
Two more habits keep this role clean. ansible-lint can fix some rules itself with ansible-lint --fix, including fqcn and name[casing]; run it on a clean Git tree and read the diff before you commit. And prefix every variable a role defines or registers with the role's name, as healthcheck_result is: the var-naming[no-role-prefix] rule in the production profile flags any that are not.
Check it worked
ansible-lintThe last line reads Passed: 0 failure(s), 0 warning(s) and Profile 'production' was required, and it passed. The exit code is 0.
Step 5 · Add a Molecule scenario that tests on this machine
A Molecule scenario is a folder of playbooks plus a molecule.yml that says where to run them. The default driver normally runs your own create and destroy playbooks to make test machines. With managed: false it skips those steps and uses the hosts you list, so here it applies the role to the machine you are on with a local connection.
That makes one rule important: when the target is your own machine, never let the role touch real paths. The scenario sets healthcheck_dir to a scratch folder in /tmp, so nothing needs sudo and the test cannot overwrite /opt/healthcheck. Create the scenario inside the role:
cd ~/ansible-test-demo/roles/healthcheck
mkdir -p molecule/default
cat > molecule/default/molecule.yml <<'YAML'
driver:
name: default
options:
managed: false
platforms:
- name: instance
provisioner:
name: ansible
env:
ANSIBLE_ROLES_PATH: "${MOLECULE_PROJECT_DIRECTORY}/.."
inventory:
host_vars:
instance:
ansible_connection: local
ansible_python_interpreter: "{{ ansible_playbook_python }}"
healthcheck_dir: /tmp/healthcheck-molecule
scenario:
test_sequence:
- syntax
- converge
- idempotence
- verify
- cleanup
YAMLThe parts that matter:
platformsnames one host,instance, andhost_varsgives it a local connection, the virtual environment's Python and the scratch install folder. Host variables apply to every playbook in the scenario, so converge and verify agree on the path.ANSIBLE_ROLES_PATHpoints at the folder above the role. Molecule setsMOLECULE_PROJECT_DIRECTORYto the role's own folder, so the converge playbook can find the role by its name,healthcheck.test_sequencelists whatmolecule testruns, in order. The full default sequence also creates and destroys instances, which this scenario does not need.
Now the converge playbook, which applies the role, and a cleanup playbook that removes the scratch folder at the end of a test run:
cat > molecule/default/converge.yml <<'YAML'
- name: Converge
hosts: all
gather_facts: false
tasks:
- name: Apply the healthcheck role
ansible.builtin.include_role:
name: healthcheck
YAML
cat > molecule/default/cleanup.yml <<'YAML'
- name: Cleanup
hosts: all
gather_facts: false
tasks:
- name: Remove the test install folder
ansible.builtin.file:
path: "{{ healthcheck_dir }}"
state: absent
YAMLApply the role once:
molecule convergeMolecule prints the ansible-playbook command it runs, then the play. The four role tasks appear as TASK [healthcheck : Create the install folder] and so on, and the recap for instance shows failed=0.
Check it worked
/tmp/healthcheck-molecule/check.sh
ls -l /tmp/healthcheck-moleculeThe script prints healthcheck: url=http://127.0.0.1/ timeout=5s. The listing shows check.sh as -rwxr-xr-x and healthcheck.conf as -rw-r--r--, the modes the role now sets.
Step 6 · Prove the role is idempotent
A role is idempotent when a second run against a host that is already configured reports no changes. That property is what lets you rerun a playbook across a fleet at any time and read the recap as the truth. Molecule checks it by running the converge playbook again and failing if any task reports changed:
molecule idempotenceCheck it worked
The output ends with default ➜ idempotence: Executed: Successful, and the recap inside it shows changed=0.
If you delete the changed_when: false line from the command task and run molecule idempotence again, it fails with Idempotence test failed because of the following tasks: and names healthcheck : Run the check once. That is the same problem no-changed-when warned about, now caught by a run. The two tools overlap on purpose: the linter catches it as you type, and Molecule catches the cases a linter cannot see, such as a template that renders differently on each run. Put the line back before you go on.
Step 7 · Write a verify playbook that checks the result
A run that succeeds and changes nothing on the second pass can still produce the wrong result: the right files with the wrong content. The verify playbook is where you check outcomes. Ask what someone would look at to decide the role worked, then assert it:
cat > molecule/default/verify.yml <<'YAML'
- name: Verify
hosts: all
gather_facts: false
tasks:
- name: Read the config file's details
ansible.builtin.stat:
path: "{{ healthcheck_dir }}/healthcheck.conf"
register: healthcheck_conf_stat
- name: Run the installed check script
ansible.builtin.command: "{{ healthcheck_dir }}/check.sh"
register: healthcheck_output
changed_when: false
- name: Check the file mode and the script output
ansible.builtin.assert:
that:
- healthcheck_conf_stat.stat.exists
- healthcheck_conf_stat.stat.mode == "0644"
- "'url=http://127.0.0.1/' in healthcheck_output.stdout"
fail_msg: "{{ healthcheck_output.stdout }}"
YAML
molecule verifyVerify playbooks are ordinary Ansible, so they are linted too, and their registered variables carry the role prefix for the same reason as the role's own.
Check it worked
The Check the file mode and the script output task prints "msg": "All assertions passed", and the output ends with default ➜ verify: Executed: Successful. To see a failure, change healthcheck_url in defaults/main.yml, run molecule converge and molecule verify, and the assert fails with the script's actual output as its message. Change it back afterwards.
Step 8 · Run the full test and lint the scenario
molecule test runs the whole sequence from molecule.yml in one go: syntax check, converge, idempotence, verify and cleanup. It is the command to run before you push, and the one a CI job runs:
molecule testLint the project again too. ansible-lint recognises Molecule's playbooks and checks them against the same production profile, and it validates molecule.yml against Molecule's schema:
cd ~/ansible-test-demo
ansible-lintCheck it worked
The Molecule output ends with a DETAILS block listing syntax, converge, idempotence, verify and cleanup, each Executed: Successful, and a recap such as default : actions=5 successful=5 ... failed=0. The cleanup has removed the scratch folder, so ls /tmp/healthcheck-molecule reports No such file or directory. ansible-lint passes the production profile with more files processed than before, because it now includes the scenario.
Step 9 · Add a container scenario for your laptop or CI
Testing on the machine you are on proves the role's logic. It does not prove the role works on a clean Ubuntu 26.04 host that has none of your tools, users or files. For that, most people give Molecule a container per test run. The Podman and Docker drivers live in the molecule-plugins package, at version 26.11.0 at the time of writing, and use the containers.podman and community.docker collections.
For Podman, with Podman already installed:
cd ~/ansible-test-demo
source .venv/bin/activate
pip install "molecule-plugins==26.11.0"
ansible-galaxy collection install containers.podmanFor Docker, use pip install "molecule-plugins[docker]==26.11.0" and ansible-galaxy collection install community.docker instead.
Add a second scenario that reuses your converge and verify playbooks. It installs to the role's real default path, because the container is thrown away afterwards:
cd ~/ansible-test-demo/roles/healthcheck
mkdir -p molecule/podman
cat > molecule/podman/molecule.yml <<'YAML'
driver:
name: podman # or: docker
platforms:
- name: ubuntu2604
image: docker.io/library/ubuntu:26.04
pre_build_image: false
provisioner:
name: ansible
env:
ANSIBLE_ROLES_PATH: "${MOLECULE_PROJECT_DIRECTORY}/.."
playbooks:
converge: ../default/converge.yml
verify: ../default/verify.yml
inventory:
host_vars:
ubuntu2604:
healthcheck_dir: /opt/healthcheck
YAML
molecule test -s podmanpre_build_image: false makes the driver build a small image from the Ubuntu one with Python added, since the stock image has none and Ansible needs it on the target. This scenario uses Molecule's full default sequence, so it creates the container, converges, checks idempotence, verifies and destroys the container. The first run downloads the Ubuntu image and its packages, a few hundred megabytes; later runs reuse the cached image.
Check it worked
molecule test -s podman ends with a DETAILS block in which create, converge, idempotence, verify and destroy are Executed: Successful, and podman ps -a (or docker ps -a) shows no leftover ubuntu2604 container. molecule test on its own still runs only the default scenario.
When you are done with the demo, delete it with rm -rf ~/ansible-test-demo and rm -rf /tmp/healthcheck-molecule. Remove the container image with podman rmi or docker rmi if you built one.
Next steps
- Go back to the roles this tutorial assumes and add a scenario to each: /tutorials/organise-ansible-work-into-roles
- Test a role that templates config files and notifies handlers, where idempotence checks catch the most: /tutorials/template-config-files-with-ansible-jinja2-and-handlers
- Check how defaults, group_vars and host_vars interact, which is what Molecule's host_vars rely on: /tutorials/organise-ansible-variables-with-group-vars-and-host-vars
- Revisit the single-playbook starting point: /tutorials/configure-a-server-with-an-ansible-playbook
Related tutorials
- Organise Ansible work into reusable rolesYou will split a one-file Ansible playbook into a base role and a web role, pull in a pinned community role from requirements.yml, and finish with a site.yml that runs cleanly a second time with changed=0.
- How to Configure a Server with an Ansible PlaybookYou will install Ansible 14 on your own computer, describe a web server's setup in a playbook, apply it over SSH, run it a second time to see that nothing changes, and preview a change with check mode before applying it.
- Template config files with Ansible, Jinja2 and handlersYou will generate an Nginx server block from a Jinja2 template with ansible-core 2.22, have Ansible test each file before installing it, reload Nginx once and only when the config changed, and review every change with a diff before it lands.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials