interview-prep

Crisp answer: Variables are input parameters for a Terraform module or root configuration. They let you reuse the same config with different values for different environments or teams.

Declaring a variable:

variable "region" {
  type        = string
  description = "AWS region to deploy into"
  default     = "eu-west-2"
}

variable "instance_type" {
  type    = string
  # No default — must be provided
}

variable "replica_count" {
  type    = number
  default = 1

  validation {
    condition     = var.replica_count >= 1 && var.replica_count <= 10
    error_message = "Replica count must be between 1 and 10."
  }
}

variable "tags" {
  type    = map(string)
  default = {}
}

variable "db_password" {
  type      = string
  sensitive = true   # Value is redacted in plan output and logs
}

variable "availability_zones" {
  type    = list(string)
  default = ["eu-west-2a", "eu-west-2b"]
}

Referencing variables:

resource "aws_instance" "web" {
  instance_type = var.instance_type
  count         = var.replica_count
  tags          = var.tags
}

Setting variable values — four ways (in order of precedence):

# 1. -var flag (highest precedence)
terraform apply -var="instance_type=t3.large"

# 2. -var-file flag
terraform apply -var-file="prod.tfvars"

# 3. terraform.tfvars or *.auto.tfvars (loaded automatically)
# prod.tfvars:
# instance_type = "t3.large"
# replica_count = 3

# 4. TF_VAR_ environment variables
export TF_VAR_db_password="secret123"
terraform apply

# 5. Interactive prompt (if no value found anywhere, Terraform asks)

tfvars file format:

# terraform.tfvars or prod.tfvars
region         = "eu-west-2"
instance_type  = "m5.large"
replica_count  = 3
availability_zones = ["eu-west-2a", "eu-west-2b", "eu-west-2c"]
tags = {
  Environment = "production"
  Team        = "platform"
}

What to say in the interview:

"Variables are the inputs to a Terraform config. You declare them with a type, optional default, optional validation, and a sensitive flag for secrets. The four ways to pass values are: -var flag, -var-file, tfvars files (auto-loaded), and TF_VAR_ environment variables. Sensitive marks the value as redacted in plan output but it still ends up in state if used directly — that's why for actual secrets I prefer the sensitive flag combined with environment variables or Vault rather than storing values in tfvars files that might get committed."


My notes