Course contentsShow
← Cloud and Infrastructure
Lesson 759 of 2,98914. Terraform FundamentalsFree lesson

Variable Validation Rules

Add validation blocks to enforce constraints and ensure variable values are correct.

Variable Validation Rules

What you'll learn: How to add validation checks to your Terraform variables to catch incorrect values before they cause infrastructure problems.

What Are Validation Rules?

Think of validation rules as guardrails for your variables—they prevent users from providing values that would break your infrastructure. Just like a form that checks if your email address has an "@" symbol, Terraform's validation blocks let you enforce constraints on variable values.

Validation happens during the terraform plan phase, catching errors early instead of during costly infrastructure provisioning.

How Validation Blocks Work

Inside a variable declaration, you add a validation block with two required arguments:

  • condition: A boolean expression that must evaluate to true
  • error_message: The message users see when validation fails
variable "instance_count" {
  type    = number
  default = 1

  validation {
    condition     = var.instance_count > 0 && var.instance_count <= 10
    error_message = "Instance count must be between 1 and 10."
  }
}

Multiple Validations

You can add multiple validation blocks to the same variable, each checking a different constraint:

variable "environment" {
  type = string

  validation {
    condition     = contains(["dev", "staging", "prod"], var.environment)
    error_message = "Environment must be dev, staging, or prod."
  }

  validation {
    condition     = length(var.environment) <= 10
    error_message = "Environment name cannot exceed 10 characters."
  }
}

Why This Matters

Without validation, incorrect variable values only fail during infrastructure creation—wasting time and potentially creating partially-built resources. Validation catches mistakes immediately, providing clear feedback about what's wrong.

Key Takeaway: Use validation blocks inside variable declarations to enforce constraints with condition expressions and helpful error_message strings, catching configuration errors before infrastructure provisioning begins.