Terraform Tutorial — Variable Types
Terraform variables support a rich type system. Understanding types ensures your configuration catches errors early and communicates clearly what inputs it expects.
Primitive Types
| Type | Example | HCL Literal |
|---|---|---|
string |
AWS region | "us-east-1" |
number |
Instance count | 3 |
bool |
Feature flag | true |
variable "region" {
type = string
default = "us-east-1"
}
variable "instance_count" {
type = number
default = 2
}
variable "enable_monitoring" {
type = bool
default = true
}
Collection Types
list(type)
An ordered collection:
variable "availability_zones" {
type = list(string)
default = ["us-east-1a", "us-east-1b"]
}
variable "ports" {
type = list(number)
default = [80, 443, 8080]
}
map(type)
Key-value pairs:
variable "tags" {
type = map(string)
default = {
Environment = "dev"
Team = "backend"
}
}
variable "instance_types" {
type = map(string)
default = {
dev = "t3.micro"
prod = "t3.large"
}
}
set(type)
Like a list but with no duplicates and no order:
variable "allowed_cidrs" {
type = set(string)
default = ["10.0.0.0/8", "172.16.0.0/12"]
}
Structural Types
object({})
A map with a defined schema:
variable "database" {
type = object({
engine = string
version = string
instance_class = string
storage_gb = number
multi_az = bool
})
default = {
engine = "postgres"
version = "15.4"
instance_class = "db.t3.micro"
storage_gb = 20
multi_az = false
}
}
tuple([])
A list with a defined sequence of types:
variable "cidr_config" {
type = tuple([string, number])
default = ["10.0.0.0", 16]
}
List of Objects
The most common complex type in real projects:
variable "users" {
type = list(object({
name = string
email = string
admin = bool
}))
default = [
{ name = "alice", email = "alice@example.com", admin = true },
{ name = "bob", email = "bob@example.com", admin = false },
]
}
The any Type
Use any when the type isn’t known in advance:
variable "settings" {
type = any
default = {}
}
⚠️ Warning: Avoid
anywhen possible. Explicit types catch errors early and serve as documentation.
What’s Next?
You know the types. Now let’s learn how to declare variables properly with descriptions, defaults, and validation.