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
YAML File Syntax Validation
- Uses
ansible-playbook --syntax-check
- Checks playbooks, role tasks, and other YAML files
- Detects structural errors before commit
- Uses
Ansible-Lint
- Additional quality check for Ansible files
- Provides hints for potential improvements
- Helps maintain best practices
Inventory Validation
- Checks inventory files with
ansible-inventory
- Identifies configuration inconsistencies
- Ensures host groups and variables are correctly defined
- Checks inventory files with
Jinja2 Template Check
- Validates syntax of
.j2
template files - Ensures templates are correctly structured
- Prevents runtime rendering errors
- Validates syntax of
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:
|
|
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
- Language: Bash Script
- Dependencies:
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!