Bird
Raised Fist0
Terraformcloud~20 mins

Variable validation rules in Terraform - Practice Problems & Coding Challenges

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
Challenge - 5 Problems
🎖️
Terraform Variable Validation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Configuration
intermediate
2:00remaining
Identify the output of a variable validation failure

Given this Terraform variable with validation, what will happen if you provide the value "test"?

variable "env" {
  type = string
  validation {
    condition     = contains(["prod", "dev", "stage"], var.env)
    error_message = "The environment must be one of: prod, dev, stage."
  }
}
ATerraform plan will fail with the error: The environment must be one of: prod, dev, stage.
BTerraform plan will succeed and use the value "test".
CTerraform plan will ignore the validation and warn but continue.
DTerraform plan will fail with a syntax error.
Attempts:
2 left
💡 Hint

Think about what happens when a variable value does not meet the validation condition.

❓ service_behavior
intermediate
2:00remaining
Determine the effect of a numeric variable validation rule

Consider this Terraform variable:

variable "instance_count" {
  type = number
  default = 3
  validation {
    condition     = var.instance_count >= 1 && var.instance_count <= 5
    error_message = "Instance count must be between 1 and 5."
  }
}

What happens if you set instance_count = 6 in your Terraform configuration?

ATerraform apply will fail with the error: Instance count must be between 1 and 5.
BTerraform apply will succeed and create 6 instances.
CTerraform apply will ignore the validation and create 6 instances.
DTerraform apply will fail with a type error.
Attempts:
2 left
💡 Hint

Validation conditions must be true for the plan to succeed.

❓ Architecture
advanced
2:00remaining
Choose the correct validation for a CIDR block variable

You want to validate a variable vpc_cidr to ensure it is a valid CIDR block in Terraform. Which validation condition correctly checks this?

Acondition = length(var.vpc_cidr) > 0
Bcondition = var.vpc_cidr != ""
Ccondition = var.vpc_cidr matches "^\d+\.\d+\.\d+\.\d+/\d+$"
Dcondition = can(cidrhost(var.vpc_cidr, 0))
Attempts:
2 left
💡 Hint

Terraform has built-in functions to test CIDR validity.

❓ security
advanced
2:00remaining
Identify the security risk of missing variable validation

What is a potential security risk if you do NOT use validation rules on a Terraform variable that accepts a list of IP addresses for firewall rules?

ATerraform will automatically block invalid IPs, so no risk exists.
BInvalid or malicious IP addresses could be allowed, opening unintended network access.
CThe variable will default to an empty list, causing no firewall rules to be created.
DTerraform will fail to apply the configuration due to missing validation.
Attempts:
2 left
💡 Hint

Think about what happens if bad input is accepted without checks.

✅ Best Practice
expert
3:00remaining
Select the best validation rule for a variable that must be a non-empty list of strings

You have a Terraform variable allowed_users that must be a list of strings and cannot be empty. Which validation block enforces this correctly?

A
validation {
  condition     = length(var.allowed_users) &gt;= 0
  error_message = "allowed_users must be a list."
}
B
validation {
  condition     = var.allowed_users != []
  error_message = "allowed_users cannot be empty."
}
C
validation {
  condition     = length(var.allowed_users) &gt; 0 &amp;&amp; alltrue([for u in var.allowed_users : can(regex("^[a-zA-Z0-9_-]+$", u))])
  error_message = "allowed_users must be a non-empty list of valid usernames."
}
D
validation {
  condition     = alltrue([for u in var.allowed_users : length(u) &gt; 0])
  error_message = "allowed_users must contain non-empty strings."
}
Attempts:
2 left
💡 Hint

Check both non-empty list and string format in the condition.

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'