Ansible with Molecule Testing — Complete Automation Guide
Introduction
Test Ansible roles with Molecule using Docker, Podman, and Vagrant drivers. This guide covers installation, configuration, and production-ready playbook patterns.
Prerequisites
# Install required collection
ansible-galaxy collection install community.general
ansible --version
Quick Start
---
- name: Ansible with Molecule Testing
hosts: all
become: true
vars:
target_env: production
tasks:
- name: Ensure dependencies installed
ansible.builtin.package:
name: "{{ item }}"
state: present
loop:
- python3
- python3-pip
- name: Configure service
ansible.builtin.template:
src: config.j2
dest: /etc/service/config.yml
mode: '0644'
notify: Restart service
handlers:
- name: Restart service
ansible.builtin.service:
name: myservice
state: restarted
Installation Playbook
- name: Install and configure
ansible.builtin.package:
name: "{{ item }}"
state: present
loop:
- package1
- package2
Configuration Management
- name: Deploy configuration
ansible.builtin.template:
src: "{{ item.src }}"
dest: "{{ item.dest }}"
owner: root
mode: '0644'
loop:
- src: main.conf.j2
dest: /etc/service/main.conf
- src: auth.conf.j2
dest: /etc/service/auth.conf
notify: Restart service
Monitoring and Health Checks
- name: Verify service health
ansible.builtin.uri:
url: "http://{{ ansible_host }}:8080/health"
status_code: 200
register: health
until: health.status == 200
retries: 10
delay: 5
Backup and Recovery
- name: Create backup
ansible.builtin.command:
cmd: "backup-tool --output /backups/{{ ansible_date_time.date }}.tar.gz"
register: backup_result
- name: Fetch backup to controller
ansible.builtin.fetch:
src: "/backups/{{ ansible_date_time.date }}.tar.gz"
dest: "./backups/{{ inventory_hostname }}/"
flat: true
Troubleshooting
| Issue | Cause | Fix |
|---|---|---|
| Connection refused | Service not running | Check service status and logs |
| Authentication failed | Wrong credentials | Verify vault-encrypted vars |
| Timeout | Resource unavailable | Increase timeout, check network |
| Idempotency issue | State mismatch | Add proper state checks |
Best Practices
- Use Vault for credentials — never hardcode passwords
- Template configs — use Jinja2 for environment-specific values
- Health checks — verify service after changes
- Backup before changes — always create restore point
- Test with Molecule — validate in isolated environment
Conclusion
Test Ansible roles with Molecule using Docker, Podman, and Vagrant drivers. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies.