# Linting and Testing — Ansible: Automate Servers with Playbooks

Source: https://www.geekswithgeeks.com/en/ansible/prod-testing

> Catch mistakes early with syntax checks, ansible-lint and role tests.

## A test ladder

Build a ladder from cheap to thorough: **`--syntax-check`** (parses the playbook), **`ansible-lint`** (flags risky or non-idiomatic patterns such as missing names, `shell` instead of modules and unpinned versions), **`--check --diff`** against staging, and **integration tests** that actually apply roles in a throwaway container or VM and verify the result, for example with **Molecule**. Run the cheap steps on every commit in CI. Failing fast keeps broken automation out of production.

## Test, scale, roll out safely

Linting, tests and rolling updates turn playbooks into dependable production tooling.

![Three habits: lint, test, roll gradually.](assets/figures/ansible/section-7-map.svg) — Figure 7.1 — Lint, test and roll gradually.

## CI steps

A minimal pipeline. `ansible-lint` and `molecule` are separate tools you install in CI. The syntax-check step is the one I ran above.

```bash
ansible-playbook -i inventories/staging site.yml --syntax-check
ansible-lint site.yml roles/
molecule test                 # per role, in a container
ansible-playbook -i inventories/staging site.yml --check --diff
```

## Test idempotence

A strong test runs the role twice and asserts the second run reports no changes. Molecule does this check by default.

**Quiz:** What is a good idempotence test?

- [ ] Run it on production first
- [ ] Run once and hope
- [ ] Delete the host
- [x] Run twice and expect zero changes on the second run

*Answer:* Run twice and expect zero changes on the second run. If a second run still changes things, the automation is not converging to a stable state.
