Explaining Data Types in Terraform with the focus on list,map,tuple and object

The aim of this page📝 is to explain data types used in terraform, focusing on complex ones, i.e. collections and structurals, i.e. list, maps, tuples and objects. There are altogether 9 types, with 4 classes with complex class having two subclasses (collection and structural). Please note that I am ignoring the set data type for the time being.

Pavol Kutaj
2 min readSep 12

--

  • The type keyword is used in Terraform to declare the type of a variable.
  • If you do not specify a type when declaring a variable in Terraform, the variable can accept any type of value.
  • However, it’s considered good practice to specify the type for clarity and to ensure the variable is used as intended.
  • If you want to declare a tuple/object variable, you need to use the type keyword.
  • This is because a tuple/object is a complex type that can contain elements of different types, and Terraform needs to know the types of each element

Typically used complex > collection types where the values stored are of the identical type

<!-- LIST COLLECTION -->
variable "aws_regions" {
type = list(string)
description = "Regions to use for AWS resources"
default = ["us-east-1", "us-east-2", "us-west-1", "us-west-2"]
}
<!-- MAP COLLECTION -->
variable "aws_instance_sizes" {
type = map(string)
description = "instance sizes to use in AWS"
default = {
small = "t3.micro"
medium = "m4.large"
large = "m4.xlarge"
}
}

Exceptionally used complex > structural types, where the values stored can be of various types

  • tuple — equivalent to list
  • object — equivalent to map
<!-- TUPLE STRUCTURAL TYPE -->
variable "example_tuple" {
type = tuple([string, number, bool])
default = ["acme1", 000, true]
}
<!-- OBJECT STRUCTURAL TYPE -->
variable "aws_instance" {
description = "AWS instance configuration"
type = object({
instance_type = string
ami = string
subnet_id = string
tags = map(string)
ebs_optimized = bool
})
default = {
instance_type = "t2.micro"
ami = "ami-0c94855ba95c574c8"
subnet_id = "subnet-0bb1c79de3EXAMPLE"
tags = { Name = "example-instance", Environment = "Test" }
ebs_optimized = false
}
}

resource "aws_instance" "example" {
ami = var.aws_instance.ami
instance_type = var.aws_instance.instance_type
subnet_id = var.aws_instance.subnet_id
ebs_optimized = var.aws_instance.ebs_optimized

tags = var.aws_instance.tags
}

Exceptionally used any

  • signal to the collection that you don’t know what type is stored in a collector
  • list(any)

Null

  • absence of a value
  • usually used to set default to variable

LINKS

--

--

Pavol Kutaj

Today I Learnt | Infrastructure Support Engineer at snowplow.io with a passion for cloud infrastructure/terraform/python/docs. More at https://pavol.kutaj.com