Module Testing and Validation
You'll learn how to verify your Terraform modules work correctly before deploying them to production.
Why Test Your Modules?
Think of Terraform modules like kitchen appliances you design for others to use. Before handing out your custom blender design, you'd test it with different ingredients, speeds, and quantities to ensure it works safely and predictably. Module testing follows the same principle—verify functionality before distribution.
Core Testing Strategies
Validation Rules
Built-in validation catches problems early. You've already learned about variable validation rules (lesson 759). Apply these to enforce module input constraints:
variable "instance_count" {
type = number
validation {
condition = var.instance_count > 0 && var.instance_count <= 10
error_message = "Instance count must be between 1 and 10."
}
}
Example Configurations
Create example configurations in an examples/ directory within your module. These serve as living documentation and test cases:
my-module/
├── main.tf
├── variables.tf
├── outputs.tf
└── examples/
├── basic/
│ └── main.tf
└── advanced/
└── main.tf
Each example should be a complete, working root module that calls your module with realistic inputs. Run terraform plan in these directories to verify behavior without deploying.
Manual Testing Workflow
- Navigate to example directory
- Run
terraform init - Run
terraform planto verify expected resources - Optionally
terraform applyto test actual deployment - Run
terraform destroyto clean up
Validation Best Practices
- Test with minimum, maximum, and typical input values
- Verify conditional resources appear/disappear correctly (lesson 809)
- Confirm outputs return expected values
- Check that dependencies resolve properly
Key Takeaway: Test modules using validation rules for inputs and example configurations that exercise different usage patterns—catching issues before users encounter them.