Write Molecule Tests for an Ansible Role Prompt
Add a Molecule test scenario to an Ansible role that converges, asserts idempotency, and verifies state, so role changes are caught before they hit real hosts.
- Target user
- Ansible automation and platform engineers
- Difficulty
- Advanced
- Tools
- Claude, ChatGPT
The prompt
You are a senior Ansible engineer who writes Molecule scenarios that prove a role converges, is idempotent, and produces the intended state. I will provide: - The role's `tasks/main.yml`, `defaults/main.yml`, and the target platforms it must support - The driver I want (docker, podman, or vagrant) and the OS images to test against - The behaviors I need verified (package installed, service running, config file contents, ports listening) Your job: 1. **Scaffold the scenario** — produce `molecule/default/molecule.yml` with the chosen driver, platforms (list each OS image), and provisioner, plus `converge.yml` that applies the role. 2. **Enforce idempotency** — confirm Molecule's default `idempotence` step is enabled and explain that a second converge must report zero changes. 3. **Write verifications** — provide `verify.yml` using Ansible asserts (or note testinfra) that check packages, services (`ansible.builtin.service_facts`), file contents, and listening ports. 4. **Cover variables** — add a second scenario or `group_vars` override to test non-default variable values, not just defaults. 5. **Wire the lint/syntax steps** — include `ansible-lint` and `yamllint` in the lint stage and `--syntax-check` expectations. 6. **Add CI** — give a CI snippet (GitHub Actions or GitLab) that runs `molecule test` on each push. Output as: (a) the `molecule/` directory tree, (b) `molecule.yml`, `converge.yml`, and `verify.yml` contents, (c) the variable-override scenario, (d) the CI job snippet. The idempotence step must pass with zero changes on second converge; treat any churn there as a role bug to fix, not a test to relax.
Related prompts
-
Make an Ansible Playbook Idempotent Prompt
Rewrite a playbook that reports 'changed' on every run into a truly idempotent one, replacing shell/command hacks with proper modules and adding correct change detection.
-
Refactor Ansible Tasks into a Reusable Role Prompt
Extract a sprawling set of inline playbook tasks into a clean, parameterized Ansible role with proper defaults, vars, handlers, and a Galaxy-standard directory layout.