Terraform Tutorial — Variables Practice Exercises

1 minute read

Practice declaring, providing, and validating Terraform variables.


Exercise 1: Variable Precedence

Task: Variable region is set to "us-east-1" as a default, "eu-west-1" in terraform.tfvars, and "ap-south-1" via -var flag. Which value does Terraform use and why?

Answer

Terraform uses "ap-south-1". The -var flag has higher precedence than terraform.tfvars, which has higher precedence than the default value.

Precedence order (highest wins): -var flag > terraform.tfvars > default value.


Exercise 2: Complex Variable Type

Task: Declare a variable called vpc_config that accepts an object with: cidr_block (string), enable_dns (bool), and public_subnets (list of strings). Provide a sensible default.

Answer
variable "vpc_config" {
  type = object({
    cidr_block     = string
    enable_dns     = bool
    public_subnets = list(string)
  })

  default = {
    cidr_block     = "10.0.0.0/16"
    enable_dns     = true
    public_subnets = ["10.0.1.0/24", "10.0.2.0/24"]
  }

  description = "VPC configuration including CIDR, DNS, and subnet layout"
}

Exercise 3: Validation

Task: Write a variable for instance_type that only allows values starting with “t3.” (like t3.micro, t3.small, t3.medium).

Answer
variable "instance_type" {
  type        = string
  description = "EC2 instance type (must be t3 family)"

  validation {
    condition     = can(regex("^t3\\.", var.instance_type))
    error_message = "Instance type must be in the t3 family (e.g., t3.micro, t3.small)."
  }
}

Exercise 4: Sensitive Variable

Task: Declare a sensitive variable for a database password. Then explain two ways to provide its value without putting it in a tracked file.

Answer
variable "db_password" {
  type        = string
  description = "Master password for the RDS instance"
  sensitive   = true
}

Two ways to provide the value:

  1. Environment variable: export TF_VAR_db_password="secret123" then terraform apply
  2. CI/CD secrets: Store in GitHub Secrets/GitLab CI Variables and inject as TF_VAR_db_password environment variable in the pipeline

Chapter Summary

In this chapter, you learned:

  • Variable types: string, number, bool, list, map, set, object, tuple
  • The variable {} block with type, default, description, sensitive, and validation
  • Five ways to provide values: defaults, terraform.tfvars, *.auto.tfvars, -var flag, TF_VAR_ env vars
  • Precedence order: env vars > -var > -var-file > auto.tfvars > terraform.tfvars > default
  • Validation blocks catch invalid input before any API calls
  • Sensitive variables hide values from plan/output (but not from state!)

Next up: Outputs — extracting values from your infrastructure.


← Sensitive Variables Outputs →