0
0
TerraformHow-ToBeginner · 3 min read

How to Use Validation in Variable in Terraform

In Terraform, you use the validation block inside a variable to define rules that check if the input value meets certain conditions. This helps catch errors early by showing a custom error message if the value is invalid.
📐

Syntax

The validation block inside a variable defines a condition and an error_message. The condition is an expression that must return true for the input to be valid. The error_message is shown if the condition fails.

  • condition: A boolean expression to validate the variable value.
  • error_message: A string message shown when validation fails.
terraform
variable "example_var" {
  type = string

  validation {
    condition     = length(var) > 3
    error_message = "The variable must be longer than 3 characters."
  }
}
💻

Example

This example shows a variable environment that only accepts the values "dev", "staging", or "prod". If a different value is given, Terraform will show the custom error message.

terraform
variable "environment" {
  type = string

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

output "env_value" {
  value = var.environment
}
Output
Error: Invalid value for variable on main.tf line 1: 1: variable "environment" { The variable "environment" must be one of: dev, staging, prod.
⚠️

Common Pitfalls

Common mistakes when using validation in Terraform variables include:

  • Using var.variable_name inside the validation block instead of just var. The correct way is to use var to refer to the variable's value.
  • Writing conditions that do not return a boolean true or false.
  • Not providing a clear error_message, which makes debugging harder.
terraform
variable "port" {
  type = number

  validation {
    # Wrong: referencing var.port inside validation condition
    condition     = var.port > 0 && var.port < 65536
    error_message = "Port must be between 1 and 65535."
  }
}

# Correct:
variable "port" {
  type = number

  validation {
    condition     = var > 0 && var < 65536
    error_message = "Port must be between 1 and 65535."
  }
}
📊

Quick Reference

Tips for using variable validation in Terraform:

  • Use validation inside variable blocks to enforce input rules.
  • Write clear boolean condition expressions using the variable value as var.
  • Always provide a helpful error_message to guide users.
  • Validation runs during terraform plan and terraform apply.

Key Takeaways

Use the validation block inside variable to enforce input rules with a boolean condition.
Reference the variable value as var inside the validation condition, not var.variable_name.
Provide a clear error_message to help users fix invalid inputs.
Validation helps catch errors early during terraform plan or apply.
Validation conditions must return true for valid inputs, false otherwise.