0
0
Terraformcloud~5 mins

Variable validation rules in Terraform - Commands & Configuration

Choose your learning style9 modes available
Introduction
When you use variables in Terraform, you want to make sure the values given are correct. Variable validation rules help check if the input fits what you expect before Terraform uses it. This stops mistakes early and keeps your infrastructure safe.
When you want to ensure a variable is a number within a certain range, like a port number between 1024 and 65535.
When you want to check that a string variable matches a specific pattern, like an environment name being only 'dev', 'test', or 'prod'.
When you want to prevent users from entering empty or invalid values for critical variables.
When you want to give clear error messages if the input does not meet your rules.
When you want to enforce rules on lists or maps, like minimum length or allowed keys.
Config File - variables.tf
variables.tf
variable "environment" {
  type = string
  description = "The deployment environment"

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

variable "port" {
  type = number
  description = "The port number for the service"

  validation {
    condition     = var.port >= 1024 && var.port <= 65535
    error_message = "Port must be between 1024 and 65535."
  }
}

variable "tags" {
  type = map(string)
  description = "Tags to apply to resources"

  validation {
    condition     = length(keys(var.tags)) > 0
    error_message = "At least one tag must be provided."
  }
}

This file defines three variables with validation rules:

  • environment: Must be one of 'dev', 'test', or 'prod'.
  • port: Must be a number between 1024 and 65535.
  • tags: Must have at least one key-value pair.

The validation block checks the condition and shows the error message if the condition is false.

Commands
This command initializes the Terraform working directory. It downloads necessary providers and prepares Terraform to run.
Terminal
terraform init
Expected OutputExpected
Initializing the backend... Initializing provider plugins... - Finding latest version of hashicorp/random... - Installing hashicorp/random v3.4.3... - Installed hashicorp/random v3.4.3 (signed by HashiCorp) Terraform has been successfully initialized!
This command checks the Terraform files for syntax errors and validates variable rules without applying changes.
Terminal
terraform validate
Expected OutputExpected
Success! The configuration is valid.
This command tries to plan changes using variable values. It will fail because 'staging' is not allowed by the environment validation rule.
Terminal
terraform plan -var='environment=staging' -var='port=8080' -var='tags={Name="example"}'
Expected OutputExpected
│ Error: Invalid value for variable │ on variables.tf line 3: │ 3: variable "environment" { │ Environment must be one of 'dev', 'test', or 'prod'. │ The given value is not allowed.
-var - Set a variable value for this run
This command plans changes with valid variable values that pass all validation rules.
Terminal
terraform plan -var='environment=prod' -var='port=8080' -var='tags={Name="example"}'
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 for this run
Key Concept

If you remember nothing else from this pattern, remember: variable validation rules stop bad input before Terraform applies changes.

Common Mistakes
Not adding a validation block to critical variables.
This allows invalid or unexpected values that can cause deployment failures or misconfigurations.
Always add validation blocks to important variables to enforce rules and provide clear error messages.
Writing validation conditions that are too complex or unclear.
Complex conditions can be hard to maintain and may cause unexpected errors.
Keep validation conditions simple and clear, using helper functions like contains() or length() when possible.
Ignoring error messages from validation failures during terraform plan.
Ignoring errors means you might deploy with wrong values, causing issues later.
Always read and fix validation errors before applying changes.
Summary
Define variables with validation blocks to check input values before use.
Use terraform init to prepare the environment and terraform validate to check syntax and validation rules.
Run terraform plan with variable values to test if they pass validation and see planned changes.