Bird
Raised Fist0
Terraformcloud~5 mins

Variable validation rules in Terraform - Commands & Configuration

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
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.

Practice

(1/5)
1. What is the main purpose of variable validation rules in Terraform?
easy
A. To speed up the Terraform apply process
B. To automatically fix errors in the Terraform code
C. To create new variables dynamically during runtime
D. To check if input values meet specific conditions before applying configuration

Solution

  1. Step 1: Understand variable validation role

    Variable validation rules ensure inputs are correct before Terraform uses them.
  2. Step 2: Identify the purpose

    They check conditions and show errors if inputs are invalid, preventing mistakes.
  3. Final Answer:

    To check if input values meet specific conditions before applying configuration -> Option D
  4. Quick Check:

    Validation checks inputs = C [OK]
Hint: Validation rules check inputs before use to avoid errors [OK]
Common Mistakes:
  • Thinking validation fixes errors automatically
  • Confusing validation with variable creation
  • Assuming validation speeds up apply
2. Which of the following is the correct syntax to add a validation rule for a variable in Terraform?
easy
A. variable "name" { validation { condition = length(var.name) > 3 error_message = "Name too short" } }
B. variable "name" { validate { condition = length(var.name) > 3 message = "Name too short" } }
C. variable "name" { validation_rule { check = length(var.name) > 3 error = "Name too short" } }
D. variable "name" { validate_rule { condition = length(var.name) > 3 error_message = "Name too short" } }

Solution

  1. Step 1: Recall Terraform variable validation syntax

    Terraform uses validation block inside variable with condition and error_message.
  2. Step 2: Match syntax with options

    variable "name" { validation { condition = length(var.name) > 3 error_message = "Name too short" } } matches correct keywords and structure exactly.
  3. Final Answer:

    variable "name" { validation { condition = length(var.name) > 3 error_message = "Name too short" } } -> Option A
  4. Quick Check:

    Correct keywords: validation, condition, error_message = A [OK]
Hint: Look for 'validation' block with 'condition' and 'error_message' keys [OK]
Common Mistakes:
  • Using 'validate' instead of 'validation'
  • Using wrong keys like 'message' or 'error'
  • Incorrect block names like 'validation_rule'
3. Given this variable definition, what happens if the input is "ab"?
variable "username" {
  type = string
  validation {
    condition = length(var.username) >= 3
    error_message = "Username must be at least 3 characters"
  }
}
medium
A. Terraform apply ignores the validation and warns only
B. Terraform apply succeeds and uses "ab" as username
C. Terraform apply fails with error: Username must be at least 3 characters
D. Terraform apply replaces "ab" with default username

Solution

  1. Step 1: Check validation condition

    The condition requires username length >= 3.
  2. Step 2: Evaluate input "ab" length

    "ab" length is 2, which is less than 3, so condition fails.
  3. Final Answer:

    Terraform apply fails with error: Username must be at least 3 characters -> Option C
  4. Quick Check:

    Input length < 3 triggers error = A [OK]
Hint: Check if input meets condition; if not, apply fails with error [OK]
Common Mistakes:
  • Assuming apply succeeds despite validation failure
  • Thinking validation only warns, not errors
  • Believing default values replace invalid input
4. Identify the error in this variable validation block:
variable "port" {
  type = number
  validation {
    condition = var.port > 0 && var.port < 65536
    error_message = "Port must be between 1 and 65535"
  }
}
medium
A. Using 'number' type instead of 'number' is invalid
B. Validation condition uses 'var.port' instead of 'self'
C. Error message is missing a period at the end
D. Validation block must be outside the variable block

Solution

  1. Step 1: Understand validation condition context

    Inside validation, use self to refer to the variable value, not var.port.
  2. Step 2: Identify incorrect usage

    The condition incorrectly uses var.port, which is not best practice.
  3. Final Answer:

    Validation condition uses 'var.port' instead of 'self' -> Option B
  4. Quick Check:

    Use 'self' in validation condition = B [OK]
Hint: Use 'self' to refer to variable value inside validation [OK]
Common Mistakes:
  • Using 'var.variable_name' inside validation condition
  • Placing validation block outside variable block
  • Ignoring syntax errors in condition
5. You want to validate a list variable so it only accepts lists with exactly 3 strings, each at least 2 characters long. Which validation condition is correct?
hard
A. condition = length(self) == 3 && all([for s in self : length(s) >= 2])
B. condition = length(self) == 3 && all([for s in self : s > 2])
C. condition = length(self) == 3 && alltrue([for s in self : s >= 2])
D. condition = length(self) == 3 && alltrue([for s in self : length(s) >= 2])

Solution

  1. Step 1: Check list length condition

    We want exactly 3 items, so length(self) == 3 is correct.
  2. Step 2: Validate each string length

    Use all() to ensure all elements satisfy length(s) >= 2.
  3. Step 3: Identify correct function and condition

    all() is the modern function; alltrue() is legacy.
  4. Final Answer:

    condition = length(self) == 3 && all([for s in self : length(s) >= 2]) -> Option A
  5. Quick Check:

    Use 'all' with length checks and list length = D [OK]
Hint: Use 'all' function and 'self' for list validation [OK]
Common Mistakes:
  • Using 'alltrue' instead of 'all'
  • Comparing strings directly to numbers
  • Using 's > 2' instead of 'length(s) >= 2'