0
0
Terraformcloud~15 mins

Variable validation rules in Terraform - Deep Dive

Choose your learning style9 modes available
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.