Andrew Mercer
on this page

Every expression in Terraform produces a value, and every value has a type. Getting types right is the single biggest lever for making modules hard to misuse: a precise type constraint on a variable rejects bad input at plan time with a clear message instead of an obscure provider error mid-apply.

The types

Primitive types

Type Examples Notes
string "canadacentral", "10" Unicode text
number 3, 3.14, -1e3 One numeric type for integers and floats (arbitrary precision)
bool true, false

Collection types (all elements share one type)

Type Literal Ordered? Duplicates? Index by
list(T) ["a", "b"] Yes Yes number [0]
set(T) toset(["a", "b"]) No No Can't index; iterate or convert
map(T) { a = 1, b = 2 } Keys sorted lexically Keys unique string ["a"]

Structural types (each element has its own type)

Type Literal Like
object({ name = string, size = number }) { name = "x", size = 3 } A struct with fixed attribute names
tuple([string, number]) ["x", 3] A fixed-length list with per-position types

The literal syntaxes [...] and {...} actually produce tuples and objects. They get converted to lists and maps when assigned somewhere that expects one. That's why ["a", 1] is legal (a tuple) but can't be assigned to a list(string) variable without converting 1.

Special values and types

  • null: absence of a value. Setting an argument to null is the same as omitting it, so the provider default applies. This is the basis of the "conditionally omit an argument" pattern in conditionals.
  • any: a placeholder in type constraints meaning "work it out from the value". list(any) means "a list of some single type, decided by the value", not "a list of mixed things".
  • Unknown: not a type but a state. A value that will be known only after apply. Shown as (known after apply).
  • Sensitive and ephemeral marks: not types either, but flags that travel with values. See variables and advanced.

Type constraints on variables

variable "subnets" {
  description = "Subnets to create in the VNet, keyed by subnet name."
  type = map(object({
    address_prefix    = string
    service_endpoints = optional(list(string), [])
    delegation        = optional(string)          # defaults to null
    private_endpoints = optional(bool, false)
  }))
}

Rules that pay off:

  • Prefer map(object({...})) over list(object({...})) for anything you'll for_each over. Map keys become stable resource addresses; list positions shift. See loops.
  • Use optional(type, default) (Terraform 1.3+) instead of hand-rolled merge(defaults, var.x). Missing attributes get the default; without a default they become null.
  • Avoid bare any in module interfaces. It moves errors from plan time to somewhere deep in the module. map(any) is acceptable for pass-through tag maps; for anything you index into, spell out the object.
  • Objects ignore extra attributes on conversion. Passing { address_prefix = "...", adress_prefix_typo = "..." } to the type above silently drops the typo. Add a validation if that matters (see below).

Catching unexpected attributes

variable "settings" {
  type = object({ sku = string, replicas = number })

  validation {
    # keys() of the *raw* input isn't available after conversion, so validate
    # a looser type instead when you need this guarantee:
    condition     = var.settings.replicas >= 1
    error_message = "replicas must be at least 1."
  }
}

If you truly need to reject unknown keys, declare the variable as map(any) and validate alltrue([for k in keys(var.x) : contains(["sku", "replicas"], k)]), then convert inside the module. Usually it's not worth it.

Automatic conversion

Terraform converts values implicitly when the target type is known:

From → To Works? Example
number → string Yes 5 → "5"
bool → string Yes true → "true"
string → number If it parses "5" → 5; "five" errors
string → bool Only "true" / "false"
tuple → list If all elements convert to one type ["a", 1] → ["a", "1"] for list(string)
object → map If all attribute values convert to one type
list ↔ set Yes (set drops duplicates and order)

Conversion surprises:

  • A conditional's two branches must convert to a common type. var.x ? ["a"] : [] is fine; var.x ? { a = 1 } : {} can fail with "inconsistent conditional result types" when the object shapes differ. See conditionals.
  • toset() on a list of objects works, but sets of objects are hard to use as for_each input because for_each needs strings as keys. Convert to a map with a for expression instead.

Explicit conversion functions

Function Use
tostring(v), tonumber(v), tobool(v) Primitive conversion
tolist(v), toset(v), tomap(v) Collection conversion
convert(v, type) Terraform 1.15+. Convert to an exact type constraint inline. Check your version's docs for the exact signature before relying on it
try(expr, fallback) Use the first expression that evaluates without error
can(expr) true if the expression evaluates without error; great in validations
type(v) Terraform 1.x console only: show a value's type when debugging

Full details are on the functions page.

Inspecting types in the console

terraform console (or tofu console) evaluates expressions against your configuration and state:

$ terraform console
> type(["a", 1])
tuple([
    string,
    number,
])
> type(tolist(["a", "b"]))
list(string)
> type({ a = 1 })
object({
    a: number,
})
> tomap({ a = 1, b = "x" })
tomap({
  "a" = "1"
  "b" = "x"
})

Terraform 1.16 adds terraform console -scope=module.network to evaluate inside a module instance, which is a big help when debugging a for expression deep in a child module.