Terraform Tutorial — Variable Validation
Variable validation lets you define custom rules that catch invalid input before Terraform makes any API calls. This is your first line of defense against misconfiguration.
The validation Block
variable "environment" {
type = string
description = "Deployment environment"
validation {
condition = contains(["dev", "staging", "prod"], var.environment)
error_message = "Environment must be dev, staging, or prod."
}
}
If someone passes environment = "test":
Error: Invalid value for variable
on variables.tf line 1:
1: variable "environment" {
Environment must be dev, staging, or prod.
Validation Examples
String Length
variable "project_name" {
type = string
validation {
condition = length(var.project_name) >= 3 && length(var.project_name) <= 20
error_message = "Project name must be between 3 and 20 characters."
}
}
Regex Pattern
variable "bucket_name" {
type = string
validation {
condition = can(regex("^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$", var.bucket_name))
error_message = "Bucket name must be 3-63 characters, lowercase, and start/end with a letter or number."
}
}
Number Range
variable "instance_count" {
type = number
validation {
condition = var.instance_count >= 1 && var.instance_count <= 10
error_message = "Instance count must be between 1 and 10."
}
}
Multiple Validations
You can have more than one validation block:
variable "cidr_block" {
type = string
validation {
condition = can(cidrhost(var.cidr_block, 0))
error_message = "Must be a valid CIDR block (e.g., 10.0.0.0/16)."
}
validation {
condition = tonumber(split("/", var.cidr_block)[1]) <= 24
error_message = "CIDR block must be /24 or larger."
}
}
Best Practices
| Practice | Why |
|---|---|
| Validate early | Catches errors before any API calls |
| Write clear error messages | Help the user fix the problem |
Use can() for safe testing |
Prevents errors in the condition itself |
| Validate formats | Ensure names comply with cloud provider rules |
What’s Next?
You can validate input. Next, let’s learn about sensitive variables — hiding passwords and API keys from plan output.