How do you cover Ansible with tests?
sobes.tech AI
Answer from AI
I use several main approaches:
-
Syntax Check:
Checks the correctness of playbooks and roles syntax before running.# Syntax check of the playbook ansible-playbook --syntax-check playbook.yml -
Idempotence:
Checks that rerunning the playbook does not change the system state after the first successful run.# Run the playbook ansible-playbook playbook.yml # Rerun with --check flag to verify changes ansible-playbook playbook.yml --checkThe output should show
changed=0 run=true. -
Molecule:
A framework for local or remote testing of Ansible roles. Allows running various testing scenarios (linting, idempotence, function testing).# Initialize Molecule in the role directory molecule init scenario -r default # Run Molecule tests molecule test -
System-level Tests (Functional Testing):
Checks that the system is in the expected state after applying Ansible. Uses:- Testinfra: Checks the state of hosts and services after configuration.
- InSpec: A Ruby-based testing framework for system state using DSL.
Molecule can integrate Testinfra:
# platforms section in molecule/default/molecule.yml platforms: - name: instance image: image_name # ... other platform settings # verifier section verifier: name: testinfra options: v: TrueExample Testinfra test (
tests/test_default.py):# import testinfra def test_nginx_is_installed(host): # Check if nginx package is installed nginx = host.package("nginx") assert nginx.is_installed def test_nginx_is_running(host): # Check if nginx service is running nginx = host.service("nginx") assert nginx.is_running def test_nginx_listens_on_port_80(host): # Check if nginx listens on port 80 assert host.socket("tcp://0.0.0.0:80").is_listening -
CI/CD Integration:
Automate test runs in CI/CD pipelines after each commit or Pull Request. For example, using Jenkins, GitLab CI, GitHub Actions.
The choice of specific approach depends on the complexity of the role/playbook and testing coverage requirements. Usually, I use a combination of these methods.