Ansible: Automate Everything from First Playbook to Production · Production Patterns: Testing, Rolling Updates and CI/CD
Testing Ansible Code: ansible-lint, Molecule and Check Mode
Catch mistakes before they reach servers: lint rules for style, Molecule for integration testing, and check mode for dry runs.
What you'll build
A testing workflow with three layers: ansible-lint for static analysis, --check --diff for dry runs against real servers, and Molecule for full role testing in disposable containers.
The idea
Ansible code that "works on my machine" can fail in production for dozens of reasons: a missing become, a wrong module parameter, a template that renders differently on another OS. Testing catches these before they cause downtime.
Three testing layers:
- ansible-lint — fast, static, runs without servers. Catches style issues, deprecated modules, missing FQCNs, and risky patterns. Runs in seconds.
- Check mode (
--check --diff) — connects to real servers but makes no changes. Shows what would change. Useful for verifying a playbook against production before applying. - Molecule — creates disposable containers (or VMs), runs the role, then verifies the result with assertions. The gold standard for role testing.
The code
Configure ansible-lint with a .ansible-lint file:
cat <<'EOF'
# .ansible-lint
---
profile: production # strictest built-in profile
warn_list:
- experimental # don't fail on experimental rules
skip_list: [] # don't skip anything by default
exclude_paths:
- .github/
- molecule/
enable_list:
- fqcn # require fully-qualified collection names
- no-changed-when # commands must declare when they change state
EOF
echo ""
echo "$ ansible-lint playbooks/"
echo ""
cat <<'LINT'
WARNING Listing 3 violation(s) that are fatal
playbooks/deploy.yml:12 Task/Handler: Install packages
fqcn[action-core]: Use FQCN for builtin module actions (apt).
Use `ansible.builtin.apt` or `ansible.legacy.apt` instead.
playbooks/deploy.yml:18 Task/Handler: Run database migration
no-changed-when: Commands should not change things if nothing needs doing.
Use `changed_when` to indicate when this task actually changes something.
playbooks/deploy.yml:24 Task/Handler: Copy config file
risky-file-permissions: File permissions unset or incorrect.
Missing mode parameter can cause unexpected file permissions.
Finished with 3 failure(s), 0 warning(s) on 1 files.
LINT
Output
# .ansible-lint --- profile: production # strictest built-in profile warn_list: - experimental # don't fail on experimental rules skip_list: [] # don't skip anything by default exclude_paths: - .github/ - molecule/ enable_list: - fqcn # require fully-qualified collection names - no-changed-when # commands must declare when they change state $ ansible-lint playbooks/ WARNING Listing 3 violation(s) that are fatal playbooks/deploy.yml:12 Task/Handler: Install packages fqcn[action-core]: Use FQCN for builtin module actions (apt). Use `ansible.builtin.apt` or `ansible.legacy.apt` instead. playbooks/deploy.yml:18 Task/Handler: Run database migration no-changed-when: Commands should not change things if nothing needs doing. Use `changed_when` to indicate when this task actually changes something. playbooks/deploy.yml:24 Task/Handler: Copy config file risky-file-permissions: File permissions unset or incorrect. Missing mode parameter can cause unexpected file permissions. Finished with 3 failure(s), 0 warning(s) on 1 files.
Run this on your computer — see “Get Started” for setup.
Fix the lint violations:
cat <<'EOF'
# BEFORE (3 violations)
- name: Install packages
apt: # ← not FQCN
name: nginx
state: present
- name: Run database migration
command: python manage.py migrate # ← no changed_when
- name: Copy config file
copy: # ← no mode
src: app.conf
dest: /etc/app/app.conf
# AFTER (0 violations)
- name: Install packages
ansible.builtin.apt: # ✓ FQCN
name: nginx
state: present
- name: Run database migration
ansible.builtin.command:
cmd: python manage.py migrate
changed_when: "'No migrations to apply' not in migration_result.stdout"
register: migration_result # ✓ changed_when
- name: Copy config file
ansible.builtin.copy:
src: app.conf
dest: /etc/app/app.conf
mode: "0644" # ✓ explicit mode
EOF
Output
# BEFORE (3 violations)
- name: Install packages
apt: # ← not FQCN
name: nginx
state: present
- name: Run database migration
command: python manage.py migrate # ← no changed_when
- name: Copy config file
copy: # ← no mode
src: app.conf
dest: /etc/app/app.conf
# AFTER (0 violations)
- name: Install packages
ansible.builtin.apt: # ✓ FQCN
name: nginx
state: present
- name: Run database migration
ansible.builtin.command:
cmd: python manage.py migrate
changed_when: "'No migrations to apply' not in migration_result.stdout"
register: migration_result # ✓ changed_when
- name: Copy config file
ansible.builtin.copy:
src: app.conf
dest: /etc/app/app.conf
mode: "0644" # ✓ explicit modeRun this on your computer — see “Get Started” for setup.
Check mode — dry run against real servers:
cat <<'EOF'
$ ansible-playbook deploy.yml --check --diff -i production.ini
PLAY [Deploy application] *****************************************************
TASK [Gathering Facts] ********************************************************
ok: [web1.example.com]
TASK [Update nginx config] ****************************************************
--- before: /etc/nginx/sites-available/app.conf
+++ after: /home/deploy/.ansible/tmp/app.conf
@@ -3,7 +3,7 @@
listen 443 ssl;
server_name app.example.com;
- proxy_pass http://127.0.0.1:8000;
+ proxy_pass http://127.0.0.1:8080;
}
changed: [web1.example.com]
TASK [Restart nginx] **********************************************************
skipping: [web1.example.com]
PLAY RECAP ********************************************************************
web1.example.com : ok=2 changed=1 unreachable=0 failed=0
EOF
Output
$ ansible-playbook deploy.yml --check --diff -i production.ini
PLAY [Deploy application] *****************************************************
TASK [Gathering Facts] ********************************************************
ok: [web1.example.com]
TASK [Update nginx config] ****************************************************
--- before: /etc/nginx/sites-available/app.conf
+++ after: /home/deploy/.ansible/tmp/app.conf
@@ -3,7 +3,7 @@
listen 443 ssl;
server_name app.example.com;
- proxy_pass http://127.0.0.1:8000;
+ proxy_pass http://127.0.0.1:8080;
}
changed: [web1.example.com]
TASK [Restart nginx] **********************************************************
skipping: [web1.example.com]
PLAY RECAP ********************************************************************
web1.example.com : ok=2 changed=1 unreachable=0 failed=0Run this on your computer — see “Get Started” for setup.
Molecule for role integration testing:
cat <<'EOF'
$ cd roles/webserver
$ molecule init scenario --driver-name docker
INFO Initializing new scenario default...
├── molecule
│ └── default
│ ├── converge.yml
│ ├── molecule.yml
│ └── verify.yml
$ cat molecule/default/molecule.yml
---
driver:
name: docker
platforms:
- name: instance
image: ubuntu:22.04
pre_build_image: true
command: /sbin/init
privileged: true
provisioner:
name: ansible
verifier:
name: ansible
$ cat molecule/default/converge.yml
---
- name: Converge
hosts: all
roles:
- role: webserver
vars:
server_name: test.example.com
app_port: 8080
$ cat molecule/default/verify.yml
---
- name: Verify
hosts: all
tasks:
- name: Check nginx is installed
ansible.builtin.package:
name: nginx
state: present
check_mode: true
register: nginx_check
failed_when: nginx_check.changed
- name: Check nginx is running
ansible.builtin.service:
name: nginx
state: started
check_mode: true
register: nginx_running
failed_when: nginx_running.changed
- name: Check config file exists
ansible.builtin.stat:
path: /etc/nginx/sites-available/app.conf
register: config_file
failed_when: not config_file.stat.exists
$ molecule test
INFO default scenario test matrix: dependency, lint, cleanup, destroy, syntax, create, prepare, converge, idempotence, verify, cleanup, destroy
INFO Running default > create
INFO Running default > converge
INFO Running default > idempotence
INFO Idempotence completed successfully.
INFO Running default > verify
INFO Verifier completed successfully.
INFO Running default > destroy
INFO Pruning extra files from scenario ephemeral directory
EOF
Output
$ cd roles/webserver
$ molecule init scenario --driver-name docker
INFO Initializing new scenario default...
├── molecule
│ └── default
│ ├── converge.yml
│ ├── molecule.yml
│ └── verify.yml
$ cat molecule/default/molecule.yml
---
driver:
name: docker
platforms:
- name: instance
image: ubuntu:22.04
pre_build_image: true
command: /sbin/init
privileged: true
provisioner:
name: ansible
verifier:
name: ansible
$ cat molecule/default/converge.yml
---
- name: Converge
hosts: all
roles:
- role: webserver
vars:
server_name: test.example.com
app_port: 8080
$ cat molecule/default/verify.yml
---
- name: Verify
hosts: all
tasks:
- name: Check nginx is installed
ansible.builtin.package:
name: nginx
state: present
check_mode: true
register: nginx_check
failed_when: nginx_check.changed
- name: Check nginx is running
ansible.builtin.service:
name: nginx
state: started
check_mode: true
register: nginx_running
failed_when: nginx_running.changed
- name: Check config file exists
ansible.builtin.stat:
path: /etc/nginx/sites-available/app.conf
register: config_file
failed_when: not config_file.stat.exists
$ molecule test
INFO default scenario test matrix: dependency, lint, cleanup, destroy, syntax, create, prepare, converge, idempotence, verify, cleanup, destroy
INFO Running default > create
INFO Running default > converge
INFO Running default > idempotence
INFO Idempotence completed successfully.
INFO Running default > verify
INFO Verifier completed successfully.
INFO Running default > destroy
INFO Pruning extra files from scenario ephemeral directoryRun this on your computer — see “Get Started” for setup.
Common mistakes
| Mistake | Fix |
|---|---|
Running only ansible-lint and skipping Molecule |
Lint catches style issues; Molecule catches runtime failures like missing dependencies or broken templates |
Testing with --check on tasks that use command/shell |
Command modules always report "changed" in check mode because Ansible can't predict their effect; use check_mode: false on specific tasks |
| Molecule tests that pass but don't assert anything | Always write explicit verify tasks; a converge that doesn't error is not proof the role works correctly |
| Not testing idempotence | Molecule's idempotence step runs the role twice and fails if anything changes on the second run — keep this enabled |
Key points
- ansible-lint catches style and correctness issues in seconds without connecting to any server.
- Check mode (
--check --diff) shows exactly what would change on real servers without applying it. - Molecule creates disposable containers, runs the role, checks idempotence, and verifies the result — the full test cycle.
- Use all three layers: lint in pre-commit hooks, check mode before production applies, Molecule in CI for role changes.
Practice questions
What are the three layers of Ansible testing and when should each be used?
Answer
- ansible-lint for fast static analysis (pre-commit and CI). 2) Check mode (--check --diff) for dry runs against real servers before production applies. 3) Molecule for full integration testing of roles in disposable containers during CI.
What does Molecule's idempotence test verify?
Answer
It runs the role twice and fails if any task reports 'changed' on the second run. This proves the role only makes changes when needed and can be safely re-run without unintended side effects.
Why do command/shell tasks always show 'changed' in check mode?
Answer
Ansible cannot predict the effect of arbitrary commands. In check mode, command and shell modules skip execution and always report changed because they don't know what the command would do. Use changed_when to tell Ansible how to detect actual changes.
Open in the app to mark lessons complete, take notes and track your progress.