Terraform 4: HCL types — primitives and collections
easy⏱ 5 mincourseterraform
Primitive types
The three primitives are string, number, and bool. A variable block declares a type and an optional default. Typed variables catch mistakes early — passing "yes" where a bool is expected fails at plan time, not at 2am.
variable "service" {
type = string
default = "orders"
}
variable "instance_count" {
type = number
default = 2
}
variable "enable_https" {
type = bool
default = true
}
Collection types: list, set, map, object
list(T) is ordered and allows duplicates; set(T) is unordered and unique; map(T) is key→value of one value type; object({...}) is a fixed shape with named, individually-typed attributes. Maps and objects are the workhorses for config that varies per environment.
variable "allowed_locations" {
type = list(string)
default = ["westus2", "eastus2"]
}
# Per-environment sizing — a map keyed by env name
variable "sku_per_env" {
type = map(string)
default = {
dev = "Standard_B1s"
uat = "Standard_B2s"
prod = "Standard_D2s_v5"
}
}
# A structured object with individually-typed attributes
variable "network" {
type = object({
address_space = list(string)
dns_servers = list(string)
enable_ddos = bool
})
default = {
address_space = ["10.0.0.0/16"]
dns_servers = ["10.0.0.4"]
enable_ddos = false
}
}
Look up map values with the index or lookup()
Read a map value by key with var.sku_per_env[var.env]. If a key might be missing, lookup(var.sku_per_env, var.env, "Standard_B1s") supplies a default instead of erroring. This one map + one index is the whole 'config per environment' pattern.
locals {
# Pick the SKU for the current environment
sku = lookup(var.sku_per_env, var.env, "Standard_B1s")
}
Look up config per environment
Model skuPerEnv as Record<string, string> (dev, uat, prod). Write skuFor(env: string): string that returns the SKU, falling back to "Standard_B1s" when the key is missing. Log skuFor("prod") and skuFor("sandbox").