Ansible Validierungs-Skript

Wie ich ein zuverlässiges Validierungstool für meine Ansible-Infrastruktur entwickelte

Initially, I planned to use Woodpecker to check my Ansible files. When the initial strategy didn’t work optimally, I developed a local script that automatically checks all changed files before each commit. What initially looked like a pragmatic adaptation evolved into an indispensable tool in my development process.

What Does the Script Do?

The script .helper/validate_ansible.sh is a comprehensive validation tool for Ansible projects. It performs various checks to ensure that my infrastructure-as-code remains clean, consistent, and error-free.

Features

  1. YAML File Syntax Validation

    • Uses ansible-playbook --syntax-check
    • Checks playbooks, role tasks, and other YAML files
    • Detects structural errors before commit
  2. Ansible-Lint

    • Additional quality check for Ansible files
    • Provides hints for potential improvements
    • Helps maintain best practices
  3. Inventory Validation

    • Checks inventory files with ansible-inventory
    • Identifies configuration inconsistencies
    • Ensures host groups and variables are correctly defined
  4. Jinja2 Template Check

    • Validates syntax of .j2 template files
    • Ensures templates are correctly structured
    • Prevents runtime rendering errors

Flexibility of Use

The script can be executed in various modes:

  • Standard: Checks only git-changed files
  • --all: Checks all files in the project
  • Selective Check: Only playbooks, inventories, or templates as needed

Integration as Git Hook

To enforce checking directly during commit, I implemented a .git/hooks/pre-commit hook:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#!/bin/bash
SCRIPT_PATH=".helper/validate_ansible.sh"

if [[ ! -x "$SCRIPT_PATH" ]]; then
  echo "Error: Script not executable"
  exit 1
fi

if ! "$SCRIPT_PATH"; then
  echo "Error: Commit aborted"
  exit 1
fi

exit 0

This hook ensures that no potentially problematic code can be committed.

Advantages

  • Automatic Quality Assurance
  • Early Error Detection
  • Consistent Code Quality
  • Seamless Integration into Development Process
  • Reduction of Manual Checks
  • Increased Infrastructure Stability

Technical Details

Conclusion

What began as a pragmatic solution developed into a robust tool. The script not only saves time but also increases the quality and reliability of my Ansible infrastructure. It’s a prime example of how small, custom-developed tools can elegantly tackle significant challenges.

Pro Tip: Invest time in automation and validation - it always pays off!