How do you test roles that depend on external services such as a database or an API?
IntermediateProductionTesting, CI/CD and Quality
Answer
Give the role a realistic dependency inside the test, rather than mocking Ansible itself.
- Add a second Molecule platform (for example a
postgrescontainer) on a shared Docker network, and point the role's variables at it. - Use
prepare.ymlto start a stub service (a small HTTP server returning canned JSON) for third-party APIs. - For cloud APIs, run the role in check mode against a sandbox account, or use a local emulator where one exists.
platforms:
- name: app
image: geerlingguy/docker-rockylinux9-ansible:latest
networks: [{ name: molecule }]
- name: db
image: postgres:16
env: { POSTGRES_PASSWORD: test }
networks: [{ name: molecule }]
Exclude the dependency container from the converge with hosts: app in converge.yml.
More on Testing, CI/CD and Quality
What does a testing pyramid look like for Ansible code?BeginnerHow do you roll out `ansible-lint` profiles across a team without blocking everyone?IntermediateWhen do you use `skip_list`, `warn_list` and `# noqa`?IntermediateHow do you set up pre-commit hooks for an Ansible repo?BeginnerHow is a Molecule scenario laid out, and what does `molecule test` actually run?IntermediateDocker, Podman or real VMs as the Molecule driver: how do you choose?Advanced