Variable Validation
Add validation blocks to reject bad input before Terraform ever calls the cloud.
Syntax
validation {
condition = ...
error_message = "..."
}A validation block inside a variable catches bad input early, with a friendly error message, instead of failing halfway through an apply.
How it works
Write a condition that must evaluate to true, plus an error_message shown when it is false.
sensitive variables
Mark secrets with sensitive = true so their values are redacted from plan and apply output.
Example
variable "environment" {
type = string
validation {
condition = contains(["dev", "staging", "prod"], var.environment)
error_message = "environment must be dev, staging, or prod."
}
}
variable "db_password" {
type = string
sensitive = true
}When to use it
- A module validates that the environment variable is only 'dev', 'staging', or 'production', preventing a typo like 'prod' from creating misnamed resources.
- A team adds a validation block on an instance_type variable to ensure engineers only pick from approved instance families, avoiding expensive instance types in dev.
- An engineer uses validation to enforce that a CIDR block variable starts with '10.' so the network team's private-only policy is enforced at plan time.
More examples
Enum validation with contains()
Rejects any value not in the allowed list, catching typos like 'prod' or 'prd' before any infrastructure is touched.
variable "environment" {
type = string
validation {
condition = contains(["dev", "staging", "production"], var.environment)
error_message = "environment must be one of: dev, staging, production."
}
}Length and format validation
Stacks two validation blocks to enforce both the length limit and the character set rules for S3 bucket names.
variable "bucket_name" {
type = string
validation {
condition = length(var.bucket_name) >= 3 && length(var.bucket_name) <= 63
error_message = "S3 bucket name must be between 3 and 63 characters."
}
validation {
condition = can(regex("^[a-z0-9][a-z0-9-]*[a-z0-9]$", var.bucket_name))
error_message = "Bucket name must use only lowercase letters, numbers, and hyphens."
}
}Numeric range validation
Validates a numeric variable to stay within an acceptable range, catching misconfigured autoscaling groups before apply.
variable "min_capacity" {
type = number
description = "Minimum number of instances in the Auto Scaling Group"
validation {
condition = var.min_capacity >= 1 && var.min_capacity <= 10
error_message = "min_capacity must be between 1 and 10."
}
}
Discussion