Instantiating variables in Terraform is a bit different than how you would do it in other languages.

In HCL, we use a .tf file extension to declare variables and assigned values, and then we assign values in a seperate file or files, with the .tfvars extension.


Defining Variables

In a variables file, like variables.tf, we can define variables with the following construction.

variable "cidr_block" {
  type        = string
  description = "The CIDR block for the subnet"
  default     = "10.0.0.0/16"
}

The file typically contains multiple variable blocks, all of which have a type, often a description, and usually a default.

Writing description can benefit hugely, to increase knowledge of each part of the infrastructure, within the team.

The variables file will serve as a single reference point used in the configuration, which enhances readability and maintainability.

It is not mandatory to create, but not doing this part, could result in a lot of backtracking further down the line.

Input Variables

Declaring a variable doesn't give it a value. Values are supplied as input, usually in a terraform.tfvars file:

cidr_block = "10.1.0.0/16"

They can also be set with -var on the command line or TF_VAR_ environment variables. If no value is given and there's no default, Terraform prompts for it.

Variable Types

Terraform has three kinds of types: primitives, collections, and structural types.

Primitives

TypeExample
string"web-1"
number2, 0.5
booltrue, false

Collections

hold multiple values of the same type:

TypeDescriptionExample
list(string)Ordered, duplicates allowed["a", "b", "a"]
set(string)Unordered, unique values["a", "b"]
map(number)Key/value pairs, same value type{ web = 2, db = 4 }

Structural types

hold values of different types:

TypeDescription
object({ name = string, cpu = number })Fixed set of named attributes
tuple([string, number, bool])Fixed-length list, type per position

Special

  • any: let Terraform infer the type. Avoid it when you can, since it defeats early error catching.
  • null: represents "no value". It's what an unset optional attribute becomes.
variable "name"    { type = string }
variable "count"   { type = number }
variable "enabled" { type = bool }
variable "azs"     { type = list(string) }
variable "ports"   { type = set(number) }
variable "sizes"   { type = map(string) }

Type Constraints

We can express a constraint to a type in order to catch early errors and bad input is caught and/or rejected early.

So within a variable, we can constrain it to a specific variable type, like so:

variable "name" {
  type = string
}

While a variable can be constrained to any type, it’s most often a primitive, like the ones we covered earlier.

For objects, we can do it like this:

variable "server" {
  type = object({
    name = string
    cpu = number
  })
}

Or more common, for lists of objects, and by adding optional we can define something as, yes, optional:

variable "servers" {
  type = list(object({
    name = string
    cpu = number
    tag = optional(string)
  }))
}

Both examples are used like so:

# single object instance
resource "aws_instance" "single" {
  instance_type = "t3.micro"
  tags = {
    Name = var.server.name
    CPU  = var.server.cpu
  }
}
# list object instance
resource "aws_instance" "many" {
  for_each      = { for s in var.servers : s.name => s }
  instance_type = "t3.micro"
  tags = {
    Name = each.value.name
    CPU  = each.value.cpu
    Tag = each.values.tag
  }
}

# terraform.tfvars
server = {
  name    = "web-1"
  cpu     = 2
}

servers = [
  { name = "web-1", cpu = 2 },
  { name = "web-2", cpu = 4, tag = "staging-environment" },
]