Bird
Raised Fist0
Terraformcloud~15 mins

Variable validation rules in Terraform - Deep Dive

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
Overview - Variable validation rules
What is it?
Variable validation rules in Terraform are checks you add to variables to make sure the values given are correct before Terraform uses them. They help catch mistakes early by enforcing conditions like value ranges or formats. This means you can stop errors before they cause problems in your infrastructure. Validation rules are written inside variable blocks and run every time you apply your Terraform configuration.
Why it matters
Without validation rules, wrong or unexpected values can cause your infrastructure to break or behave unpredictably. This can lead to downtime, security risks, or wasted resources. Validation rules act like a safety net, ensuring only valid inputs are accepted. This saves time, reduces errors, and makes your infrastructure more reliable and easier to manage.
Where it fits
Before learning variable validation rules, you should understand basic Terraform variables and how to declare them. After mastering validation rules, you can explore advanced Terraform features like modules, dynamic blocks, and custom providers that rely on clean input data.
Mental Model
Core Idea
Variable validation rules are like gatekeepers that check if input values meet your rules before letting them into your infrastructure.
Think of it like...
Imagine a club bouncer checking IDs at the door to make sure only people of the right age get in. Validation rules do the same for your variables, only letting in values that follow your rules.
┌─────────────────────────────┐
│        Input Variable       │
└─────────────┬───────────────┘
              │
              ▼
┌─────────────────────────────┐
│    Validation Rules Check   │
│  (conditions like length,   │
│   allowed values, patterns) │
└─────────────┬───────────────┘
              │
     ┌────────┴─────────┐
     │                  │
     ▼                  ▼
┌───────────────┐  ┌───────────────┐
│ Value Accepted│  │ Value Rejected│
│  (used by TF) │  │  (error stops)│
└───────────────┘  └───────────────┘
Build-Up - 6 Steps
1
FoundationUnderstanding Terraform Variables
🤔
Concept: Learn what Terraform variables are and how they store input values.
Terraform variables let you pass data into your configuration to make it flexible. You declare variables with a type and optional default value. For example: variable "region" { type = string default = "us-west-1" } This variable holds the AWS region name. You can override it when running Terraform.
Result
You can reuse the same configuration in different environments by changing variable values.
Understanding variables is essential because validation rules apply directly to these inputs to ensure correctness.
2
FoundationBasic Variable Validation Syntax
🤔
Concept: Introduce the syntax to add validation rules inside a variable block.
Inside a variable block, you add a 'validation' block with a 'condition' and an 'error_message'. For example: variable "instance_count" { type = number validation { condition = var.instance_count > 0 error_message = "instance_count must be greater than zero." } } This checks that the number is positive before Terraform applies changes.
Result
Terraform will stop with an error if the condition is false, preventing bad inputs.
Knowing the syntax lets you start protecting your variables from invalid values early.
3
IntermediateUsing Complex Conditions in Validation
🤔Before reading on: do you think validation conditions can only check simple comparisons, or can they use functions and multiple checks? Commit to your answer.
Concept: Validation conditions can use complex expressions, combining multiple checks and functions.
Terraform supports expressions in validation conditions. You can use logical operators like && (and), || (or), and functions like length(), contains(), regex(), etc. For example: variable "environment" { type = string validation { condition = contains(["dev", "staging", "prod"], var.environment) error_message = "environment must be one of dev, staging, or prod." } } This ensures the environment variable is one of the allowed values.
Result
You can enforce detailed rules, like allowed sets or string patterns, improving input quality.
Understanding that validation supports complex logic lets you create precise rules tailored to your needs.
4
IntermediateValidation with Custom Error Messages
🤔Before reading on: do you think Terraform shows generic errors for validation failures, or can you customize the error message? Commit to your answer.
Concept: You can customize the error message shown when validation fails to make it clear and helpful.
The 'error_message' field in the validation block lets you write a clear message. For example: variable "port" { type = number validation { condition = var.port >= 1024 && var.port <= 65535 error_message = "Port must be between 1024 and 65535." } } This helps users understand exactly what went wrong.
Result
Users get clear feedback, making it easier to fix input mistakes quickly.
Knowing how to write good error messages improves user experience and reduces troubleshooting time.
5
AdvancedValidation for Complex Types and Collections
🤔Before reading on: do you think validation rules only work on simple types like strings and numbers, or can they validate lists and maps too? Commit to your answer.
Concept: Validation rules can check complex types like lists, maps, and objects using expressions.
For example, to validate a list of strings: variable "allowed_ips" { type = list(string) validation { condition = alltrue([for ip in var.allowed_ips : can(regex("^\\d+\\.\\d+\\.\\d+\\.\\d+$", ip))]) error_message = "All allowed_ips must be valid IPv4 addresses." } } This checks every IP in the list matches the IPv4 pattern.
Result
You can enforce rules on every element inside collections, ensuring data consistency.
Understanding validation on collections unlocks powerful input checks for real-world complex data.
6
ExpertLimitations and Workarounds of Validation Rules
🤔Before reading on: do you think Terraform validation rules can access external data or depend on other variables? Commit to your answer.
Concept: Validation rules only work on the variable's own value and cannot access external data or other variables directly.
Terraform validation runs during plan time and only sees the variable's value. It cannot call external APIs or check other variables. To work around this, you can use modules with input validation or write custom pre-check scripts outside Terraform. Also, validation errors stop the plan, so complex logic should be balanced to avoid blocking legitimate changes.
Result
You learn the boundaries of validation and how to design around them for robust infrastructure.
Knowing these limits prevents frustration and encourages designing validation that fits Terraform's model.
Under the Hood
Terraform evaluates validation rules during the plan phase after variable values are assigned but before any resources are created or changed. The 'condition' expression is evaluated using Terraform's expression language. If the condition returns false, Terraform halts and shows the 'error_message'. This prevents invalid inputs from proceeding to resource creation, avoiding runtime errors or misconfigurations.
Why designed this way?
Validation rules were designed to catch errors early in the workflow, improving safety and user feedback. They are limited to the variable's own value to keep evaluation simple and deterministic during planning. Allowing external calls or cross-variable checks would complicate the plan phase and could cause unpredictable behavior or delays.
┌───────────────┐
│ User Provides │
│ Variable Value│
└───────┬───────┘
        │
        ▼
┌─────────────────────┐
│ Terraform Plan Phase │
│  - Assign Variables  │
│  - Evaluate Validation ──────────────┐
└─────────────┬─────────┘             │
              │                       │
      ┌───────┴───────┐         ┌─────┴─────┐
      │ Condition True│         │ Condition │
      │ (Pass)       │         │ False     │
      └───────┬───────┘         └─────┬─────┘
              │                       │
              ▼                       ▼
    ┌─────────────────┐      ┌─────────────────────┐
    │ Continue Plan &  │      │ Stop Plan & Show    │
    │ Apply Changes    │      │ Error Message       │
    └─────────────────┘      └─────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do you think Terraform validation rules can check values of other variables? Commit to yes or no.
Common Belief:Validation rules can access and compare other variables to enforce cross-variable constraints.
Tap to reveal reality
Reality:Validation rules only evaluate the single variable's value they belong to and cannot reference other variables.
Why it matters:Trying to enforce cross-variable rules inside validation causes confusion and errors; you must handle such logic elsewhere, or it won't work.
Quick: Do you think validation rules run after resources are created? Commit to yes or no.
Common Belief:Validation rules run after Terraform creates or updates resources to catch errors late.
Tap to reveal reality
Reality:Validation rules run during the plan phase before any resource changes happen.
Why it matters:Knowing this prevents wasted time fixing errors after costly resource changes and helps catch problems early.
Quick: Do you think validation rules can call external APIs or scripts? Commit to yes or no.
Common Belief:Validation rules can perform external checks like calling APIs or scripts to validate inputs.
Tap to reveal reality
Reality:Validation rules cannot call external systems; they only use Terraform's expression language on the variable's value.
Why it matters:Expecting external checks in validation leads to design mistakes; external validation must happen outside Terraform.
Quick: Do you think validation rules can fix invalid inputs automatically? Commit to yes or no.
Common Belief:Validation rules can correct or adjust invalid inputs to valid ones automatically.
Tap to reveal reality
Reality:Validation rules only check and reject invalid inputs; they do not modify or fix them.
Why it matters:Assuming automatic fixes can cause overlooked errors; users must provide correct inputs or handle fixes manually.
Expert Zone
1
Validation conditions are evaluated with Terraform's full expression language, allowing powerful but sometimes complex logic that can impact plan performance if overused.
2
Validation errors stop the entire plan, so overly strict or complex validations can block legitimate changes; balancing strictness and flexibility is key.
3
Validation rules do not support dynamic or runtime data, so for inputs depending on external state, consider using data sources or pre-apply scripts.
When NOT to use
Avoid using validation rules when input depends on external systems or other variables; instead, use external validation scripts or Terraform modules with input checks. Also, do not rely on validation for complex business logic better handled in CI/CD pipelines or configuration management tools.
Production Patterns
In production, teams use validation rules to enforce environment-specific constraints, like allowed regions or instance sizes. They combine validation with modules to ensure consistent inputs across projects. Custom error messages improve developer experience. Some use pre-commit hooks or CI pipelines to run additional validation beyond Terraform's capabilities.
Connections
Input Validation in Web Forms
Similar pattern of checking user inputs before processing.
Understanding how web forms validate inputs helps grasp why Terraform validates variables early to prevent errors downstream.
Type Systems in Programming Languages
Validation rules act like runtime type checks and constraints.
Knowing type systems clarifies how validation enforces expected data shapes and values, improving program correctness.
Quality Control in Manufacturing
Both enforce standards before products proceed to next stages.
Seeing validation as quality control highlights its role in preventing defects and ensuring reliability.
Common Pitfalls
#1Writing validation conditions that reference other variables.
Wrong approach:validation { condition = var.min_size < var.max_size error_message = "min_size must be less than max_size" }
Correct approach:Handle cross-variable checks outside validation, for example in a module or pre-apply script, because validation cannot access other variables.
Root cause:Misunderstanding that validation rules only see their own variable's value.
#2Using overly complex validation expressions that slow down Terraform plans.
Wrong approach:validation { condition = length([for v in var.list : can(regex("^\\d+$", v)) && v != "0"]) == length(var.list) error_message = "All list items must be non-zero digits." }
Correct approach:Simplify validation or split checks into multiple variables or external scripts to keep plan performance acceptable.
Root cause:Not realizing that complex expressions increase plan evaluation time.
#3Assuming validation fixes invalid inputs automatically.
Wrong approach:validation { condition = var.port >= 1024 && var.port <= 65535 error_message = "Port must be between 1024 and 65535." } # expecting Terraform to adjust port if invalid
Correct approach:Validation only rejects invalid inputs; users must provide correct values or handle defaults explicitly.
Root cause:Confusing validation with input sanitization or correction.
Key Takeaways
Terraform variable validation rules check input values early to prevent errors during infrastructure deployment.
Validation conditions use Terraform's expression language and can enforce simple to complex rules on variable values.
Validation only sees the variable's own value and cannot access other variables or external data.
Clear custom error messages improve user understanding and speed up fixing input mistakes.
Knowing validation limits helps design robust infrastructure code and avoid common pitfalls.

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'