Working with Complex Variable Types
What you'll learn: How to define and validate advanced variable structures like objects, tuples, and deeply nested types to create more sophisticated Terraform configurations.
Beyond Simple Types
You've already worked with primitives (strings, numbers, bools) and collections (lists, maps). Now it's time to combine these into complex variable types that mirror real-world infrastructure requirements. Think of this as moving from describing a single book (string) to describing an entire library catalog with sections, shelves, and metadata.
Objects and Tuples
Objects let you define structured data with named fields of different types:
variable "server_config" {
type = object({
name = string
vcpus = number
memory = number
public = bool
disk_ids = list(string)
})
}
Tuples are like lists but with a fixed sequence of specific types:
variable "server_details" {
type = tuple([string, number, bool]) # name, port, ssl_enabled
}
Nested Structures
You can nest objects within objects or lists of objects:
variable "network" {
type = object({
vpc_cidr = string
subnets = list(object({
name = string
cidr = string
zone = string
}))
})
}
Validation Rules
Complex types can include validation to catch errors early:
variable "instance" {
type = object({
size = string
count = number
})
validation {
condition = var.instance.count > 0 && var.instance.count < 100
error_message = "Instance count must be between 1 and 99."
}
}
Key Takeaway: Complex variable types—objects, tuples, and nested structures—let you model sophisticated infrastructure requirements with type safety and built-in validation, making your configurations more reliable and self-documenting.