Agrega TESTING.md con documentación exhaustiva sobre: - Molecule (framework oficial de testing) - Ansible Lint (análisis estático) - Testinfra (testing de infraestructura con Python) - YAML Lint (validación de sintaxis) - Estrategias de CI/CD con GitHub Actions y GitLab CI - Comandos útiles y mejores prácticas - Estrategia de testing por fases para Abyaya.la 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
9.2 KiB
Testing en Abyaya.la
Esta guía documenta las estrategias y herramientas de testing para infraestructura como código (IaC) basada en Ansible.
Índice
- Testing de Ansible
- Validación y Sintaxis
- Testing de Infraestructura
- CI/CD para Ansible
- Recursos Adicionales
Testing de Ansible
Molecule (Framework oficial - RECOMENDADO)
Molecule es el framework oficial para testing de roles de Ansible. Permite ejecutar tests unitarios, de integración y verificar idempotencia.
Documentación Oficial:
- Documentación principal: https://ansible.readthedocs.io/projects/molecule/
- Getting Started: https://ansible.readthedocs.io/projects/molecule/getting-started/
- Guía de escenarios: https://ansible.readthedocs.io/projects/molecule/configuration/
Características:
- Tests unitarios de roles individuales
- Tests de integración
- Tests de idempotencia (verificar que ejecutar dos veces da el mismo resultado)
- Soporte para Docker/Podman para simular entornos
Instalación:
pip install molecule molecule-docker
Uso básico:
cd roles/rap
molecule init scenario
molecule test
Ansible Lint
Herramienta de análisis estático que verifica mejores prácticas y patrones comunes en playbooks y roles de Ansible.
Documentación:
- Documentación principal: https://ansible-lint.readthedocs.io/
- Catálogo de reglas: https://ansible-lint.readthedocs.io/rules/
Instalación:
pip install ansible-lint
Uso:
# Verificar un playbook específico
ansible-lint deploy.yml
# Verificar todos los archivos del proyecto
ansible-lint
# Verificar un rol específico
ansible-lint roles/proxy/
Testinfra
Framework de testing de infraestructura escrito en Python. Permite verificar el estado real de los servidores después del despliegue.
Documentación:
- Documentación principal: https://testinfra.readthedocs.io/
- Ejemplos: https://testinfra.readthedocs.io/en/latest/examples.html
Instalación:
pip install testinfra
Ejemplo de test:
# tests/test_vpn.py
def test_tinc_is_running(host):
"""Verificar que el servicio Tinc está corriendo"""
tinc = host.service("tinc@comun")
assert tinc.is_running
assert tinc.is_enabled
def test_vpn_interface_exists(host):
"""Verificar que la interfaz VPN existe"""
assert host.interface("comun").exists
def test_vpn_ip_assigned(host):
"""Verificar que la IP VPN está asignada"""
comun = host.interface("comun")
assert comun.addresses[0].startswith("10.13.12.")
def test_nginx_is_running(host):
"""Verificar que Nginx está corriendo"""
nginx = host.service("nginx")
assert nginx.is_running
def test_port_443_listening(host):
"""Verificar que el puerto 443 está escuchando"""
assert host.socket("tcp://0.0.0.0:443").is_listening
Ejecución:
# Ejecutar tests contra un host
testinfra --hosts=ssh://root@hetzner tests/test_vpn.py
# Ejecutar con Ansible inventory
testinfra --ansible-inventory=hosts.production tests/
Validación y Sintaxis
YAML Lint
Validador de sintaxis YAML con verificación de estilos y buenas prácticas.
Documentación:
- Repositorio: https://github.com/adrienverge/yamllint
- Configuración: https://yamllint.readthedocs.io/en/stable/configuration.html
Instalación:
pip install yamllint
Uso:
# Validar archivos específicos
yamllint deploy.yml abyayala.yml
# Validar todos los YAML del proyecto
yamllint *.yml roles/*/tasks/*.yml roles/*/templates/*.yml
Configuración (.yamllint):
extends: default
rules:
line-length:
max: 120
indentation:
spaces: 2
Ansible Syntax Check (Built-in)
Verificación de sintaxis integrada en Ansible.
Documentación:
- Testing strategies: https://docs.ansible.com/ansible/latest/reference_appendices/test_strategies.html
- Syntax check: https://docs.ansible.com/ansible/latest/cli/ansible-playbook.html#cmdoption-ansible-playbook-syntax-check
Uso:
# Verificar sintaxis de un playbook
ansible-playbook deploy.yml --syntax-check
# Dry-run (simular sin ejecutar)
ansible-playbook deploy.yml --check
# Dry-run con diff de cambios
ansible-playbook deploy.yml --check --diff
Testing de Infraestructura
InSpec (Chef)
Framework de testing de infraestructura enterprise. Alternativa más robusta a Testinfra.
Documentación:
- Documentación principal: https://docs.chef.io/inspec/
Características:
- Lenguaje DSL específico para infraestructura
- Compliance as Code
- Perfiles de seguridad predefinidos
CI/CD para Ansible
GitHub Actions
Documentación:
- GitHub Actions para Ansible: https://github.com/marketplace/actions/run-ansible-playbook
Ejemplo de workflow:
# .github/workflows/test.yml
name: Test Ansible Playbooks
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: '3.x'
- name: Install dependencies
run: |
pip install ansible ansible-lint yamllint molecule molecule-docker
- name: Run YAML Lint
run: yamllint .
- name: Run Ansible Lint
run: ansible-lint
- name: Syntax check
run: ansible-playbook deploy.yml --syntax-check
- name: Run Molecule tests
run: |
cd roles/rap
molecule test
GitLab CI
Documentación:
- GitLab CI para Ansible: https://docs.gitlab.com/ee/ci/examples/ansible/
Ejemplo de pipeline:
# .gitlab-ci.yml
stages:
- lint
- test
lint:yaml:
stage: lint
image: python:3.9
script:
- pip install yamllint
- yamllint .
lint:ansible:
stage: lint
image: python:3.9
script:
- pip install ansible-lint
- ansible-lint
test:syntax:
stage: test
image: python:3.9
script:
- pip install ansible
- ansible-playbook deploy.yml --syntax-check
test:molecule:
stage: test
image: python:3.9
services:
- docker:dind
script:
- pip install molecule molecule-docker
- cd roles/rap && molecule test
Recursos Adicionales
Guías y Tutoriales
- Testing Ansible Roles with Molecule: https://www.digitalocean.com/community/tutorials/how-to-test-ansible-roles-with-molecule-on-ubuntu-20-04
- Developing and Testing Ansible Roles with Molecule and Podman (Serie de artículos): https://www.ansible.com/blog/developing-and-testing-ansible-roles-with-molecule-and-podman-part-1
Best Practices
- Ansible Best Practices: https://docs.ansible.com/ansible/latest/tips_tricks/ansible_tips_tricks.html
- Ansible Style Guide: https://docs.ansible.com/ansible/latest/dev_guide/style_guide/
Libros
- Ansible for DevOps (Jeff Geerling): https://www.ansiblefordevops.com/
- Capítulos relevantes sobre testing y CI/CD
Estrategia de Testing Recomendada para Abyaya.la
Fase 1: Inmediato (Quick Wins)
-
Validación de sintaxis
ansible-playbook deploy.yml --syntax-check -
YAML Lint
pip install yamllint yamllint . -
Ansible Lint
pip install ansible-lint ansible-lint
Fase 2: Corto Plazo (1-2 semanas)
-
Molecule para roles críticos
- Empezar con
roles/rap(VPN es crítico) - Continuar con
roles/proxy(punto de entrada público) - Agregar
roles/certbot(seguridad SSL)
- Empezar con
-
Pre-commit hooks
pip install pre-commit # Crear .pre-commit-config.yaml pre-commit install
Fase 3: Largo Plazo (1-2 meses)
-
Testinfra para verificación post-despliegue
- Tests de conectividad VPN
- Tests de disponibilidad de servicios
- Tests de configuración de firewall
- Tests de certificados SSL
-
CI/CD Pipeline
- GitHub Actions o GitLab CI
- Tests automáticos en cada push
- Tests de integración en staging
-
Tests de integración end-to-end
- Despliegue completo en entorno de prueba
- Verificación de flujo completo: VPN → Proxy → Servicio
Comandos Útiles de Testing
# Testing rápido de sintaxis
ansible-playbook deploy.yml --syntax-check
# Dry-run (ver qué cambiaría sin aplicar)
ansible-playbook deploy.yml --check --diff -e "host=hetzner alt=abyayala"
# Verificar sintaxis YAML
yamllint *.yml roles/
# Análisis estático con ansible-lint
ansible-lint deploy.yml
# Test de un rol específico con Molecule
cd roles/rap && molecule test
# Verificación post-despliegue con Testinfra
testinfra --hosts=ssh://root@hetzner tests/
# Ver qué tareas se ejecutarían
ansible-playbook deploy.yml --list-tasks -e "host=hetzner alt=abyayala"
# Ejecutar solo con tags específicos en check mode
ansible-playbook deploy.yml --check --tags=vpn -e "host=hetzner alt=abyayala"
Contribuir
Al agregar nuevos roles o modificar existentes:
- Ejecutar ansible-lint antes de commit
- Verificar sintaxis con --syntax-check
- Si es un rol crítico, agregar tests de Molecule
- Documentar casos de prueba en este archivo