Custom Validation Rules
What you'll learn: How to enforce organizational standards by writing custom validation rules for your Terraform variables and outputs.
What Are Custom Validation Rules?
Custom validation rules let you define specific constraints beyond basic type checking. Think of them as gatekeepers—just as a bouncer checks IDs at a club entrance, validation rules verify that input values meet your organization's standards before Terraform proceeds with any infrastructure changes.
Why They Matter
You've already learned about variable blocks and basic validation rules. Now you'll extend that knowledge to create sophisticated checks that enforce policies like:
- Ensuring S3 bucket names follow naming conventions
- Requiring instance types from an approved list
- Validating CIDR blocks fall within allowed ranges
- Checking tag values match organizational patterns
How to Implement Custom Validation
You add a validation block inside your variable declaration with two components: a condition (must evaluate to true) and an error_message (displayed when validation fails).
variable "environment" {
type = string
description = "Deployment environment"
validation {
condition = contains(["dev", "staging", "prod"], var.environment)
error_message = "Environment must be dev, staging, or prod."
}
}
variable "instance_size" {
type = string
validation {
condition = can(regex("^(small|medium|large)$", var.instance_size))
error_message = "Instance size must be small, medium, or large."
}
}
These checks run during terraform plan, catching policy violations before any resources are created.
Key Takeaway: Custom validation rules transform Terraform variables from simple inputs into policy enforcement points, catching configuration errors early and ensuring infrastructure consistently meets your organization's standards.