Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 37 ยท The HCL Language

Types and Values in Terraform

Learn Terraform's type system: string, number, bool, list, set, map, tuple, object, null and any, automatic type conversion, and how to write type constraints.

Every value in Terraform has a type, and the type decides what you can do with it. Understanding the type system early saves you from the most common error messages ("Inappropriate value for attribute", "Incorrect attribute value type", "Invalid index"). Terraform's types are few and regular, and Terraform converts between them automatically when it is safe to do so.

All hcl blocks are read-only; the runnable Python stand-ins imitate type checking and conversion so you can see the rules at work.

Primitive types

There are three primitive types:

HCL
locals {
  name    = "web-1"     # string
  port    = 8080        # number (integers and decimals are both "number")
  enabled = true        # bool
}

Strings are sequences of Unicode characters. Numbers can be whole or fractional with no separate integer type. Booleans are true or false. Any of them may also be null, which means "absent": an argument set to null behaves as if you had not written it, and the provider's default applies.

Collection types

A collection holds several values of the same type.

  • list(type): an ordered sequence, indexed from zero. ["a", "b", "c"]. Duplicates allowed.
  • set(type): an unordered collection of unique values. No indexing.
  • map(type): key to value, where keys are strings and all values share one type. { env = "prod", team = "web" }.
HCL
locals {
  zones = ["eu-central-1a", "eu-central-1b"]       # list(string)
  ports = toset([80, 443, 80])                      # set(number) with 2 items
  tags  = { env = "prod", team = "web" }            # map(string)
}

Access with square brackets or dots: local.zones[0], local.tags["env"], or local.tags.env for simple keys. Use a set when order is meaningless and duplicates would be a bug, for example a set of security group IDs or the keys you pass to for_each.

Structural types

A structural type groups values that may have different types.

  • object({ attr = type, ... }): a fixed set of named attributes, each with its own type. Think of a record.
  • tuple([type, type, ...]): a fixed-length sequence where each position has its own type.
HCL
locals {
  server = {                  # object({ name = string, cpus = number, public = bool })
    name   = "web-1"
    cpus   = 2
    public = true
  }
  row = ["web-1", 2, true]    # tuple([string, number, bool])
}

In practice you write { ... } and [ ... ] literals, and Terraform infers whether they are maps or objects, lists or tuples. A literal { a = 1, b = 2 } is an object, but it converts to map(number) when the context asks for one. The same applies to ["a", "b"], a tuple that converts to list(string).

any and dynamic values

any is a placeholder in type constraints (variables, module inputs) meaning "any type, decided by what is passed in." It is handy for generic modules but hides mistakes, so prefer a precise type when you know it.

Type constraints

You declare the type a variable accepts with a type constraint:

HCL
variable "ports" {
  type = list(number)
}

variable "tags" {
  type = map(string)
}

variable "server" {
  type = object({
    name   = string
    cpus   = number
    public = optional(bool, false)   # optional with a default
  })
}

optional(type, default) makes an object attribute optional. Without a default it becomes null. Constraints can nest: list(object({ name = string, port = number })) is a common shape for a list of rules. See input variables for using them.

Python A type checker for Terraform-style types (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The messages mirror the shape of real Terraform errors: they point to the exact path inside a nested value, which is the best way to find the faulty element.

Automatic type conversion

Terraform converts values when the context demands a different type and the conversion is unambiguous:

From To Result
"8080" (string) number 8080
8080 (number) string "8080"
"true" / "false" bool true / false
true string "true"
tuple ["a","b"] list(string) list
object {a=1} map(number) map
list set duplicates removed, order lost
set list arbitrary but stable order (sorted for primitives)

It does not convert "yes" to a bool or "abc" to a number; those are errors. When a value has mixed types, for example [1, "two"], Terraform tries to find one type that fits all elements and converts them: that list becomes list(string) because numbers convert to strings.

Python Implicit conversions (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Explicit conversion functions

When you want to be explicit use tostring, tonumber, tobool, tolist, toset and tomap:

HCL
locals {
  unique_zones = toset(["a", "b", "a"])    # {"a", "b"}
  port_number  = tonumber("8080")
  as_list      = tolist(local.unique_zones)
}

The classic use is converting a list to a set to feed for_each (see count and for_each).

Working with null

null represents the absence of a value. Passing null to an optional resource argument means "use the provider's default" (or leave it unset). It is the usual way to turn an argument on or off with a conditional:

HCL
resource "aws_instance" "web" {
  key_name = var.use_key ? var.key_name : null
}

Finding a value's type

terraform console is an interactive prompt that evaluates expressions against your configuration. The type() function exists only in the console:

TEXT
> type({ a = 1, b = "x" })
object({
    a: number,
    b: string,
})
> type(["a", "b"])
tuple([
    string,
    string,
])

(Example output.) The console is the quickest way to experiment with expressions and functions without applying anything.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which type is an unordered collection of unique values?

    A set has no order and no duplicates, which suits for_each keys. A list is ordered and may repeat values.
  2. 2. What is the difference between map(string) and object({ a = string })?

    Maps are homogeneous collections with arbitrary keys. Objects are records with a fixed set of attributes and per-attribute types.
  3. 3. What does Terraform do when a string argument receives the number 8080?

    Numbers and bools convert to strings automatically. The reverse works only if the string looks like a number or bool.
  4. 4. What does assigning null to an optional resource argument mean?

    null means absent. Terraform behaves as if you omitted the argument, so the provider's default applies.

Summary

  • Primitive types: string, number, bool; any of them can be null.
  • Collections hold one element type: list, set, map. Structural types mix types: object, tuple.
  • Type constraints (list(number), object({...}), optional()) document and enforce inputs.
  • Terraform converts automatically when it is safe: number or bool to string, numeric-looking strings to number, tuples to lists.
  • toset, tolist, tomap, tonumber convert explicitly.
  • terraform console lets you test expressions and inspect types.

Next: Expressions, Operators and Conditionals