Day 34intermediateMar 6, 2026

Validate Terraform Variables at Plan Time

Catch bad variable values at plan time instead of waiting for the cloud provider to reject them during apply.

terraformvalidationbest-practices
Share:

What

Terraform variable validation blocks let you add custom rules that check variable values before any resources are created. Each validation block contains a condition expression and an error_message that is displayed when the condition is false. You can add multiple validation blocks to a single variable.

Why It Matters

Without validation, invalid variable values only surface when the cloud provider API rejects them during terraform apply. This wastes time and can leave your infrastructure in a partially applied state. Validation catches errors early at plan time with clear, custom error messages.

Example

variable "environment" {
  type        = string
  description = "Deployment environment"

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

variable "instance_type" {
  type        = string
  description = "EC2 instance type"

  validation {
    condition     = can(regex("^t3\\.", var.instance_type))
    error_message = "Only t3 instance types are allowed (e.g., t3.micro, t3.small)."
  }
}

# Running plan with invalid values:
# terraform plan -var="environment=test"
# Error: Invalid value for variable
# Environment must be one of: dev, staging, prod.
hcl

Common Mistake

Not adding validation rules and only discovering invalid values when the cloud provider rejects them during apply, potentially leaving infrastructure in a broken half-applied state.

Quick Fix

Add validation blocks to every variable that has known constraints. Use contains() for allowed lists, can(regex()) for pattern matching, and comparison operators for numeric ranges. Terraform evaluates these before any API calls.

Key Takeaways

  • 1Validation blocks catch bad values at plan time
  • 2condition = expression that must be true
  • 3error_message = what the user sees on failure
  • 4Use contains() for allowed value lists
  • 5Use can(regex()) for pattern matching

Was this tip helpful?

Help us improve the DevOpsPath daily collection

Share: