Type Constraints
Someone runs Crumb's configuration with web_count = "lots". Without a type, that string sails in and fails much later with a confusing message. With a type, Terraform rejects it at the door and says why.
The rule
Type the shape at the door; wrong shapes never get in.
Primitive types:
string—"t3.micro"number—2,0.5bool—true,false
Collection types, where every element has the same type:
list(string)— ordered, may repeat:["a", "b", "a"]set(string)— unordered, unique: good forfor_eachmap(number)— keys to values of one type:{ images = 30, logs = 90 }
Structural types, where elements can differ:
object({ size = string, disk_gb = number })— fixed named attributes, each with its own typetuple([string, number])— fixed positions, each with its own type
And any, which accepts anything and lets Terraform infer a type. Use it sparingly.
variable "web_count" {
type = number
default = 1
}
variable "bucket_names" {
type = set(string)
default = ["images", "menus", "logs"]
}
variable "server" {
type = object({
size = string
disk_gb = optional(number, 20)
})
}optional(number, 20) makes that attribute optional inside the object, filling in 20 when it is left out.
Terraform converts where it safely can: "2" becomes 2 for a number, "true" becomes true for a bool, and a list becomes a set. When conversion is impossible, like "lots" to a number, you get an error before any plan is made.
The shortcut
Ask three questions in order: One value or many? If many, same type or different? If same, does order or duplication matter?
Number of servers
One value, a count:
number.
The trap: using map for mixed settings. A map(string) forces the disk size to be a string, and a missing attribute is not caught. Objects check both names and types.
Drills
Answer fast — trust the rule.
Which type suits a list of unique bucket names used with for_each?
What happens if "3" is passed to a variable of type number?
Which type fits settings with a string size and a number disk_gb?
What does optional(number, 20) inside an object type do?
When is a value that fails its type constraint reported?
Remember
- Primitives: string, number, bool. Collections: list, set, map. Structures: object, tuple.
- Shortcut: one or many? same type or mixed? order and duplicates?
- Trap: map for mixed settings; use an object.
