0
0
Terraformcloud~10 mins

Variable validation rules in Terraform - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a variable with a description.

Terraform
variable "region" {
  type        = string
  description = [1]
}
Drag options to blanks, or click blank then click option'
Aaws_region
B"AWS region to deploy resources"
Cstring
Ddefault = "us-east-1"
Attempts:
3 left
💡 Hint
Common Mistakes
Using variable name instead of a description string
Omitting quotes around the description
2fill in blank
medium

Complete the code to add a validation rule that ensures the variable is not empty.

Terraform
variable "environment" {
  type = string

  validation {
    condition     = [1]
    error_message = "Environment cannot be empty."
  }
}
Drag options to blanks, or click blank then click option'
Avar.environment == ""
Bvar.environment != null
Clength(var.environment) > 0
Dvar.environment == null
Attempts:
3 left
💡 Hint
Common Mistakes
Checking for equality with empty string instead of length
Using null checks which are not appropriate for strings
3fill in blank
hard

Fix the error in the validation condition to allow only values 'dev', 'staging', or 'prod'.

Terraform
variable "stage" {
  type = string

  validation {
    condition     = contains([[1]], var.stage)
    error_message = "Stage must be one of: dev, staging, prod."
  }
}
Drag options to blanks, or click blank then click option'
A["dev", "staging", "prod"]
B"dev", "staging", "prod"
Cdev, staging, prod
D"dev staging prod"
Attempts:
3 left
💡 Hint
Common Mistakes
Using a string instead of a list
Omitting square brackets around the list
4fill in blank
hard

Fill both blanks to validate a number variable is between 1 and 10 inclusive.

Terraform
variable "instance_count" {
  type = number

  validation {
    condition     = var.instance_count [1] 1 && var.instance_count [2] 10
    error_message = "Instance count must be between 1 and 10."
  }
}
Drag options to blanks, or click blank then click option'
A>=
B<=
C>
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using strict greater than or less than which excludes boundary values
Swapping the operators
5fill in blank
hard

Fill all three blanks to validate a list variable contains only allowed strings.

Terraform
variable "allowed_zones" {
  type = list(string)

  validation {
    condition     = alltrue([for zone in var.allowed_zones : zone [1] [[2]]])
    error_message = "Zones must be one of the allowed values."
  }
}
Drag options to blanks, or click blank then click option'
Ain
B"us-east-1a", "us-east-1b", "us-east-1c"
Ccontains
D"us-west-2a", "us-west-2b", "us-west-2c"
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'contains' incorrectly as an operator instead of a function
Not using a for expression to check each item
Providing the wrong list of zones