Testing and Validation
Table of Contents
Introduction: The Untested Deployment
Why Test Infrastructure Code?
The Cost of Infrastructure Bugs
What Testing Prevents
Testing Benefits
Levels of Testing
Testing Pyramid for Infrastructure
Input Validation
Basic Validation
Complex Validation Rules
Multiple Validation Rules
Precondition and Postcondition Checks
terraform validate
What It Checks
What It Doesn't Check
Usage
Common Errors Caught by Validate
Validate in CI/CD
terraform fmt - Code Formatting
What It Does
Usage
Before and After
In CI/CD
Pre-commit Hook
terraform plan - The First Test
What Plan Tests
Safe Plan Testing
Plan in CI/CD
Plan Assertions
Static Analysis and Linting
TFLint
Checkov
tfsec
Terrascan
Unit Testing with Terratest
What is Terratest?
Install Go
Project Structure
Simple Terratest Example
Complex Test Example
Integration Testing
Integration Test Structure
Integration Test Example
Contract Testing
What is Contract Testing?
Contract Test Example
Policy as Code
Open Policy Agent (OPA)
Sentinel (Terraform Cloud)
Real-World Example: Comprehensive Testing Pipeline
Project Structure
Validation Script
Linting Script
Test Script
Makefile
GitHub Actions Workflow
CI/CD for Terraform
GitOps Workflow
Pipeline Stages
Test-Driven Development (TDD) for Infrastructure
TDD Process
Example: TDD for a Module
Common Testing Patterns
Pattern 1: Parameterized Tests
Pattern 2: Fixture-Based Testing
Pattern 3: Golden File Testing
Testing Best Practices
1. Test Pyramid
2. Test What Matters
3. Parallel Tests
4. Clean Up
5. Use Unique Names
6. Fast Feedback
7. Test in Isolation
What I Learned About Testing Infrastructure
1. Testing Prevents Disasters
2. Validation is Your First Line of Defense
3. The Test Pyramid Applies to Infrastructure
4. terraform plan IS a Test
5. Policy as Code Prevents Accidents
6. CI/CD Makes Testing Automatic
7. TDD Works for Infrastructure
Next Steps
Practice Exercises
Coming Up Next
Last updated