Terraform
Basics & Fundamentals
- Infrastructure as Code (IaC)
- Declarative Syntax in IaC
- Terraform Configuration Files
- Terraform CLI
- Terraform Init
- Terraform Plan
- Terraform Apply
- Terraform Destroy
Providers & Resources
Variables & Outputs
π Terraform Variable Validation: Ensuring Inputs Match Specific Conditions
Terraform is a powerful Infrastructure as Code (IaC) tool that allows teams to automate cloud resource provisioning. While defining infrastructure, Terraform uses variables to accept input values such as region names, VM sizes, passwords, or database configurations.
But hereβs the challenge: What if someone enters invalid input?
- Imagine setting
instance_type = "t3.invalid"
β deployment fails. - Or entering a too short password β security risk.
- Or entering a region name that doesnβt exist β wasted time.
π This is where Terraform Variable Validation comes in.
Variable validation ensures that all inputs meet predefined conditions before Terraform executes. It acts like a gatekeeper, preventing errors, enforcing security, and saving debugging time.
π What is Terraform Variable Validation?
Terraform Variable Validation allows you to:
- Define rules (conditions) for variable values.
- Validate those values before Terraform runs.
- Show custom error messages if validation fails.
π Think of it like a teacher checking your homework before grading itβinvalid answers are rejected upfront.
π₯οΈ Syntax of Variable Validation
variable "name" { type = string description = "Description of the variable"
validation { condition = <boolean expression> error_message = "Custom error message if condition fails" }}
- condition β Expression that must evaluate to
true
. - error_message β Displayed when validation fails.
π₯οΈ 3 Unique Example Programs for Terraform Variable Validation
β Example 1: Validate AWS Region Name
Code
variable "aws_region" { type = string description = "AWS region to deploy resources"
validation { condition = contains(["us-east-1", "us-west-2", "eu-central-1"], var.aws_region) error_message = "Region must be us-east-1, us-west-2, or eu-central-1." }}
Test Cases
- β
Input:
us-east-1
β Pass - β Input:
ap-south-2
β Error β"Region must be us-east-1, us-west-2, or eu-central-1."
π Helps avoid invalid region names.
β Example 2: Validate Instance Type
Code
variable "instance_type" { type = string description = "EC2 instance type"
validation { condition = can(regex("^t[2-3].[a-z0-9]+$", var.instance_type)) error_message = "Instance type must start with t2 or t3, e.g., t2.micro or t3.small." }}
Test Cases
- β
Input:
t2.micro
β Pass - β
Input:
t3.medium
β Pass - β Input:
m5.large
β Error β"Instance type must start with t2 or t3."
π Useful for ensuring only approved instance families are used.
β Example 3: Validate Password Strength
Code
variable "db_password" { type = string description = "Database password"
validation { condition = length(var.db_password) >= 8 && can(regex("[A-Z]", var.db_password)) error_message = "Password must be at least 8 characters and contain an uppercase letter." }}
Test Cases
- β
Input:
StrongPass1
β Pass - β Input:
weak
β Error β"Password must be at least 8 characters and contain an uppercase letter."
π Enforces basic security policies directly in Terraform.
π Advanced Validation Examples
β Example 4: Numeric Range Validation
variable "replica_count" { type = number
validation { condition = var.replica_count >= 1 && var.replica_count <= 5 error_message = "Replica count must be between 1 and 5." }}
π Prevents misconfigurations like scaling replicas to 0 or 100.
β Example 5: Allowed Values from a List
variable "environment" { type = string
validation { condition = contains(["dev", "staging", "prod"], var.environment) error_message = "Environment must be one of: dev, staging, prod." }}
π Guarantees only valid environments are selected.
β Example 6: Complex Object Validation
variable "server_config" { type = object({ cpu = number memory = number })
validation { condition = var.server_config.cpu >= 2 && var.server_config.memory >= 4 error_message = "Server must have at least 2 CPUs and 4GB memory." }}
π Ensures infrastructure sizing requirements are respected.
π Real-World Use Cases
- Cloud Region Restrictions β Only allow specific approved regions.
- Cost Control β Restrict instance types to cost-efficient ones.
- Security Compliance β Enforce password policies.
- Standardization β Environments like
dev
,stage
,prod
only. - Resource Scaling Limits β Avoid overspending by capping replicas or nodes.
π§ How to Remember Variable Validation (Exam & Interview Prep)
π Mnemonic: βValidation = Guardrailsβ
- Inputs are like cars.
- Validation adds guardrails, preventing them from going off-road.
Quick Pointers for Exams
- Validation block has condition + error_message.
- If condition = false β Terraform stops execution immediately.
- Syntax is always inside the
variable
block.
Common Interview Questions
-
Q: Why use variable validation in Terraform? A: To prevent invalid inputs, enforce policies, and catch errors early.
-
Q: Can you validate complex objects? A: Yes, by combining conditions on object attributes.
-
Q: What happens if validation fails? A: Terraform stops execution and displays the custom error message.
π― Why Is It Important to Learn This Concept?
- Prevents Costly Errors β Wrong region, instance type, or scaling config can be very expensive.
- Saves Debugging Time β Catches mistakes early before running
terraform apply
. - Improves Security β Password rules and access controls are enforced at IaC level.
- Standardizes Deployments β Teams follow the same rules, reducing misconfigurations.
- Certification & Interview Ready β Frequently tested in Terraform Associate Exam and real DevOps interviews.
π Comparison: Variables vs Validation
Feature | Variables | Validation |
---|---|---|
Purpose | Accept input values | Enforce conditions on those inputs |
Error Handling | Accepts all values | Stops execution on invalid input |
Example | variable "region" | Restrict region to [βus-east-1β] |
π₯οΈ Consuming Validated Variables
You can test values using CLI:
terraform apply -var="aws_region=ap-south-1"
If invalid:
Error: Invalid value for variableRegion must be us-east-1, us-west-2, or eu-central-1.
π Stops execution β saves time.
π Conclusion
Terraform Variable Validation is like a safety net for Infrastructure as Code.
- It ensures inputs follow business rules, security policies, and cost guidelines.
- Prevents human errors before deployment.
- Plays a key role in automation pipelines and team collaboration.
- Essential for Terraform certifications, real-world projects, and interviews.
π If you remember one line: βVariables collect input, but validation makes sure the input is correct.β