0
0
Terraformcloud~5 mins

Variable validation blocks in Terraform - Commands & Configuration

Choose your learning style9 modes available
Introduction
When you create variables in Terraform, you want to make sure the values given are correct. Variable validation blocks help check these values before Terraform uses them. This stops mistakes early and keeps your infrastructure safe.
When you want to ensure a variable is within a certain range, like a number between 1 and 10.
When you want to check that a string variable matches a specific pattern, like a region name.
When you want to prevent users from entering invalid values that could break your setup.
When you want to give clear error messages if the input is wrong.
When you want to enforce rules on variables without writing extra scripts.
Config File - variables.tf
variables.tf
variable "instance_count" {
  type        = number
  description = "Number of instances to create"
  default     = 3

  validation {
    condition     = var.instance_count >= 1 && var.instance_count <= 5
    error_message = "The instance_count must be between 1 and 5."
  }
}

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

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

This file defines two variables with validation blocks:

  • instance_count: Must be a number between 1 and 5. If not, Terraform shows the error message.
  • environment: Must be one of the allowed strings: dev, staging, or prod.

The validation block checks the value and shows a clear message if it is wrong.

Commands
This command sets up Terraform in the current folder. It downloads necessary plugins and prepares the environment.
Terminal
terraform init
Expected OutputExpected
Initializing the backend... Initializing provider plugins... - Finding latest version of hashicorp/aws... - Installing hashicorp/aws v4.0.0... - Installed hashicorp/aws v4.0.0 (signed by HashiCorp) Terraform has been successfully initialized! You may now begin working with Terraform. Try running "terraform plan" to see any changes.
This command checks if the Terraform files are valid. It also runs the variable validation blocks to check if the default values meet the rules.
Terminal
terraform validate
Expected OutputExpected
Success! The configuration is valid.
This command tries to plan the infrastructure using an invalid instance_count value (6). Terraform will run the validation and show an error.
Terminal
terraform plan -var='instance_count=6' -var='environment=dev'
Expected OutputExpected
Error: Invalid value for variable on variables.tf line 2: 2: variable "instance_count" { The instance_count must be between 1 and 5.
-var - Set a variable value from the command line
This command plans the infrastructure with valid variable values. The validation passes and Terraform shows the planned actions.
Terminal
terraform plan -var='instance_count=3' -var='environment=prod'
Expected OutputExpected
Refreshing Terraform state in-memory prior to plan... No changes. Infrastructure is up-to-date. This means that Terraform did not detect any differences between your configuration and real physical resources that exist.
-var - Set a variable value from the command line
Key Concept

If you remember nothing else from this pattern, remember: variable validation blocks stop wrong inputs early by checking values and showing clear errors before applying changes.

Common Mistakes
Not using validation blocks and relying on users to input correct values.
This can cause Terraform to apply wrong or harmful configurations, leading to failures or broken infrastructure.
Always add validation blocks to important variables to enforce rules and prevent mistakes.
Writing validation conditions that are too complex or incorrect syntax.
Terraform will fail to parse the file or the validation won't work as expected, causing confusion.
Keep validation conditions simple and test them with terraform validate and terraform plan.
Not providing clear error_message in the validation block.
Users get generic errors and don't know how to fix their input.
Always write clear, friendly error messages explaining what is wrong and how to fix it.
Summary
Use terraform init to prepare Terraform and download plugins.
Use terraform validate to check configuration and variable validations.
Use terraform plan with -var flags to test variable values and see validation errors.
Variable validation blocks help catch wrong inputs early with clear messages.