Variable Types
Variables can be typed as string, number, bool, list, map, or complex object types.
Syntax
type = list(string)
type = map(number)
type = object({ name = string })Giving a variable a type lets Terraform validate inputs and produce clearer errors.
Primitive types
string— text.number— integers or decimals.bool—trueorfalse.
Collection and structural types
list(string)— ordered values.map(string)— key/value pairs.set(string)— unique unordered values.object({...})— a fixed structure with named attributes.
Example
variable "availability_zones" {
type = list(string)
default = ["us-east-1a", "us-east-1b"]
}
variable "db_config" {
type = object({
engine = string
instance_class = string
multi_az = bool
})
default = {
engine = "postgres"
instance_class = "db.t3.micro"
multi_az = false
}
}When to use it
- A module uses type = list(string) for allowed_ips so callers supply multiple CIDR blocks as a list without constructing a comma-separated string.
- A platform team uses type = map(string) for common_tags so every resource block can spread the map directly into its tags argument.
- An engineer uses type = object({...}) for a database config variable to group related settings and get type-checking on each nested field.
More examples
List and map variable types
Declares a list variable for CIDR blocks and a map variable for tag key-value pairs, both with usable defaults.
variable "allowed_cidrs" {
type = list(string)
default = ["10.0.0.0/8", "192.168.1.0/24"]
}
variable "common_tags" {
type = map(string)
default = {
Project = "my-app"
ManagedBy = "terraform"
}
}Object type variable
Uses an object type to group related database settings, providing schema validation on each field's type.
variable "database" {
type = object({
instance_class = string
allocated_storage = number
multi_az = bool
})
default = {
instance_class = "db.t3.micro"
allocated_storage = 20
multi_az = false
}
}Using typed variables in resources
Accesses individual fields of the object variable using dot notation to populate resource arguments.
resource "aws_db_instance" "app" {
instance_class = var.database.instance_class
allocated_storage = var.database.allocated_storage
multi_az = var.database.multi_az
engine = "mysql"
username = "admin"
password = var.db_password
}
Discussion