Bird
Raised Fist0
Terraformcloud~10 mins

Variable validation blocks in Terraform - Step-by-Step Execution

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
Process Flow - Variable validation blocks
Define variable with validation block
Input value provided
Check validation condition
Accept value
Stop deployment
Terraform checks the variable's input against the validation condition. If it passes, deployment continues; if not, it stops with an error.
Execution Sample
Terraform
variable "env" {
  type = string
  validation {
    condition     = contains(["dev", "prod"], var.env)
    error_message = "env must be 'dev' or 'prod'"
  }
}
This variable 'env' only accepts 'dev' or 'prod'. If another value is given, Terraform shows an error and stops.
Process Table
StepInput ValueValidation ConditionCondition ResultAction
1"dev"contains(["dev", "prod"], "dev")trueAccept value, continue deployment
2"test"contains(["dev", "prod"], "test")falseError: env must be 'dev' or 'prod', stop deployment
💡 Deployment stops if validation condition is false to prevent invalid inputs.
Status Tracker
VariableStartAfter Step 1After Step 2
var.envundefined"dev" (valid)"test" (invalid, error)
Key Moments - 2 Insights
Why does Terraform stop deployment when the validation fails?
Terraform stops because the validation block's condition returned false (see execution_table step 2), which means the input does not meet the required rules.
Can the validation block change the variable value?
No, the validation block only checks the value. It does not modify it. If invalid, it stops deployment instead (see execution_table).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what happens when the input value is "dev"?
ADeployment stops with an error
BValue is changed to "prod" automatically
CValue is accepted and deployment continues
DTerraform ignores the validation block
💡 Hint
Check execution_table row 1 under 'Action' column
At which step does the validation condition become false?
AStep 1
BStep 2
CValidation never fails
DBefore step 1
💡 Hint
Look at execution_table 'Condition Result' column
If the validation condition was changed to allow "test", how would the execution table change?
AStep 2 would accept "test" and continue deployment
BStep 1 would fail instead
CBoth steps would stop deployment
DNo change in execution table
💡 Hint
Think about how condition result affects action in execution_table
Concept Snapshot
Terraform variable validation blocks check input values.
Syntax: validation { condition = <bool>; error_message = "msg" }
If condition is false, deployment stops with error.
Validation does not change values, only verifies them.
Use to enforce allowed inputs and prevent mistakes.
Full Transcript
Terraform variable validation blocks let you set rules for input values. When you run Terraform, it checks if the input meets the condition. If yes, deployment continues. If no, Terraform stops and shows the error message. This helps avoid mistakes by catching wrong inputs early. The validation block only checks values; it does not change them. For example, if you want a variable to be only 'dev' or 'prod', you write a condition to check that. If someone enters 'test', Terraform will stop and show an error. This process ensures your infrastructure is configured correctly before applying changes.

Practice

(1/5)
1. What is the main purpose of a validation block inside a Terraform variable?
easy
A. To check if the input value meets specific rules before applying the configuration
B. To assign a default value to the variable
C. To declare the variable type
D. To output the variable value after deployment

Solution

  1. Step 1: Understand variable validation purpose

    The validation block is used to enforce rules on input values to prevent invalid configurations.
  2. Step 2: Differentiate from other variable features

    Default values assign fallback values, type declares data type, and output shows results, but validation specifically checks input correctness.
  3. Final Answer:

    To check if the input value meets specific rules before applying the configuration -> Option A
  4. Quick Check:

    Validation block purpose = input checking [OK]
Hint: Validation blocks check inputs before use [OK]
Common Mistakes:
  • Confusing validation with default value assignment
  • Thinking validation outputs variable values
  • Mixing validation with type declaration
2. Which of the following is the correct syntax to add a validation block inside a Terraform variable?
easy
A. variable "example" { validate { condition = length(var.example) > 0 error = "Must not be empty" } }
B. variable "example" { validation { condition = length(var.example) > 0 error_message = "Must not be empty" } }
C. variable "example" { validation { check = length(var.example) > 0 message = "Must not be empty" } }
D. variable "example" { validation { condition = length(example) > 0 error_message = "Must not be empty" } }

Solution

  1. Step 1: Identify correct block and attribute names

    The correct block is validation with attributes condition and error_message.
  2. Step 2: Check variable references and syntax

    Inside the condition, use var.example to refer to the variable value. variable "example" { validation { condition = length(var.example) > 0 error_message = "Must not be empty" } } matches this exactly.
  3. Final Answer:

    variable "example" { validation { condition = length(var.example) > 0 error_message = "Must not be empty" } } -> Option B
  4. Quick Check:

    Validation syntax = correct block and attributes [OK]
Hint: Use 'validation' block with 'condition' and 'error_message' [OK]
Common Mistakes:
  • Using 'validate' instead of 'validation'
  • Using wrong attribute names like 'check' or 'error'
  • Referencing variable without 'var.' prefix
3. Given this variable declaration:
variable "port" {
  type = number
  validation {
    condition     = var.port >= 1024 && var.port <= 65535
    error_message = "Port must be between 1024 and 65535"
  }
}

What happens if you set port = 80 when applying Terraform?
medium
A. Terraform will apply successfully with port 80
B. Terraform will prompt to enter a valid port
C. Terraform will ignore the validation and use default port
D. Terraform will fail with error: Port must be between 1024 and 65535

Solution

  1. Step 1: Analyze the validation condition

    The condition requires the port to be between 1024 and 65535 inclusive.
  2. Step 2: Check the input value against the condition

    Port 80 is less than 1024, so the condition fails.
  3. Step 3: Understand Terraform behavior on validation failure

    Terraform stops and shows the error message from error_message.
  4. Final Answer:

    Terraform will fail with error: Port must be between 1024 and 65535 -> Option D
  5. Quick Check:

    Validation fails = error message shown [OK]
Hint: Validation blocks stop apply if condition is false [OK]
Common Mistakes:
  • Assuming Terraform applies anyway
  • Thinking default values are used automatically
  • Expecting interactive prompts for invalid input
4. Identify the error in this variable validation block:
variable "env" {
  type = string
  validation {
    condition     = var.env == "dev" || "prod"
    error_message = "env must be 'dev' or 'prod'"
  }
}
medium
A. Validation blocks cannot use logical OR operators
B. The error_message attribute is misspelled
C. The condition syntax is incorrect; it should compare both values explicitly
D. The variable type should be list, not string

Solution

  1. Step 1: Review the condition expression

    The condition var.env == "dev" || "prod" is invalid because "prod" alone is always true.
  2. Step 2: Correct the condition syntax

    It should be var.env == "dev" || var.env == "prod" to compare both values explicitly.
  3. Final Answer:

    The condition syntax is incorrect; it should compare both values explicitly -> Option C
  4. Quick Check:

    Logical OR needs full comparisons [OK]
Hint: Use full comparisons on both sides of OR [OK]
Common Mistakes:
  • Writing incomplete logical expressions
  • Assuming string alone works as condition
  • Confusing error_message spelling
5. You want to validate a list variable users so it must have at least 2 unique names and none can be empty strings. Which validation block correctly enforces this?
hard
A. validation { condition = length(var.users) >= 2 && length(distinct(var.users)) == length(var.users) && alltrue([for u in var.users : u != ""]) error_message = "Users must have 2+ unique non-empty names" }
B. validation { condition = length(var.users) > 2 && distinct(var.users) != [] error_message = "Users must have 2+ unique names" }
C. validation { condition = length(var.users) >= 2 && var.users != [""] error_message = "Users must not be empty" }
D. validation { condition = length(var.users) >= 2 && length(var.users) == length(distinct(var.users)) error_message = "Users must have unique names" }

Solution

  1. Step 1: Check list length and uniqueness

    Condition requires at least 2 items and all must be unique, so length(var.users) >= 2 and length(distinct(var.users)) == length(var.users) ensure this.
  2. Step 2: Ensure no empty strings

    The alltrue([for u in var.users : u != ""]) checks every user is not empty.
  3. Step 3: Compare options

    validation { condition = length(var.users) >= 2 && length(distinct(var.users)) == length(var.users) && alltrue([for u in var.users : u != ""]) error_message = "Users must have 2+ unique non-empty names" } includes all these checks correctly; others miss empty string check or uniqueness properly.
  4. Final Answer:

    validation { condition = length(var.users) >= 2 && length(distinct(var.users)) == length(var.users) && alltrue([for u in var.users : u != ""]) error_message = "Users must have 2+ unique non-empty names" } -> Option A
  5. Quick Check:

    All conditions combined = validation { condition = length(var.users) >= 2 && length(distinct(var.users)) == length(var.users) && alltrue([for u in var.users : u != ""]) error_message = "Users must have 2+ unique non-empty names" } [OK]
Hint: Combine length, distinct, and alltrue for list validation [OK]
Common Mistakes:
  • Missing empty string check
  • Using > 2 instead of >= 2 for minimum count
  • Not verifying uniqueness correctly