Terraform 12: Input variables (type, default, description, validation)
easy⏱ 5 mincourseterraform
Declaring a variable
A variable block gives a value a name, a type constraint, an optional default, and a description. Reference it anywhere as var.<name>. With no default, the variable is required — Terraform prompts for it (or errors in CI) until it's supplied.
# variables.tf
variable "environment" {
type = string
description = "Deployment environment (dev, uat, or prod)."
# No default => required. The caller must supply it.
}
variable "location" {
type = string
default = "westus2"
description = "Azure region for all resources."
}
variable "instance_count" {
type = number
default = 1
description = "How many app instances to run."
}
# Using them
resource "azurerm_resource_group" "app" {
name = "myorg-orders-${var.environment}-rg"
location = var.location
}
Types: primitives and complex types
Terraform types come in primitives (string, number, bool) and complex types (list(...), set(...), map(...), object({...}), tuple([...])). A typed object is great for grouping related settings so callers can't forget a field.
variable "tags" {
type = map(string)
default = { team = "platform", cost_center = "1000" }
}
variable "app" {
type = object({
name = string
replicas = number
public = bool
})
default = {
name = "orders"
replicas = 2
public = false
}
}
validation blocks fail fast
A validation block runs a condition and, if it's false, aborts with your error_message — before any resource is touched. Use it to enforce allow-lists and formats. contains([...], var.x) is the classic allow-list check.
variable "environment" {
type = string
description = "Deployment environment."
validation {
condition = contains(["dev", "uat", "prod"], var.environment)
error_message = "environment must be one of: dev, uat, prod."
}
}
variable "instance_count" {
type = number
default = 1
validation {
condition = var.instance_count >= 1 && var.instance_count <= 10
error_message = "instance_count must be between 1 and 10."
}
}
Model a validated variable
Mirror the HCL above in TypeScript. Create an environment object with type: "string", an allowed array ["dev", "uat", "prod"], and an isValid(value) method returning a boolean (the contains(...) check). Log environment.isValid("prod") (should be true) and environment.isValid("staging") (should be false).