Type constraints and complex variables

Intermediate · 28 min

Declare list, map, set, tuple and object variables, use optional attributes with defaults, and know when Terraform converts types for you and when it stops.

Before thisInput variables and validation

Tech Tutorials with Piyush · 42 min · from 13:58

Type constraints and complex variables

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Tech Tutorials with PiyushReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Primitive types are `string`, `number` and `bool`. Collections are `list(T)`, `set(T)` and `map(T)`, where every element has type T.
  • Structural types, `tuple([...])` and `object({...})`, mix element types. An object is a fixed set of named attributes, each with its own type.
  • `optional(type, default)` inside an object lets callers omit an attribute. It came in with Terraform 1.3.
  • Terraform converts between similar types, such as the string `"5"` to a number, and errors when the conversion cannot work.
  • Avoid `any`. The docs say it is very rarely correct, and it removes the checks types exist to give.

Why types matter at the boundary

A module takes subnets as an input. One caller passes a list of IDs, another a map of name to ID, a third a single string. The module iterates over it, and what happens depends on which caller wrote it: a wrong-shaped value fails twenty lines down, in an error that mentions a function the caller never wrote.

Type constraints fix that by checking the shape of an input where it enters. A wrong value fails at the variable, with the variable’s name in the message.

The types

Primitives are string, number and bool.

Collections hold many values of one type: list(string) is an ordered sequence, set(string) is unordered and unique, map(string) has string keys and string values.

Structural types hold a fixed shape with mixed types. object({ name = string, port = number }) has exactly those named attributes. tuple([string, number]) is a fixed-length list with a type per position, and you will rarely write one.

Written from the Terraform docs and not run:

variable "subnet_ids" {
  type = list(string)
}

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

variable "service" {
  type = object({
    name = string
    port = optional(number, 8080)
    tls  = optional(bool, false)
  })
}

A caller can now pass { name = "api" } and receive port = 8080 and tls = false inside the module. Terraform 1.3 introduced optional() for object attributes, with a default as the second argument. I confirmed that in the v1.3 changelog on GitHub. Without a default, an omitted optional attribute is null, and the docs promise that an optional attribute with a non-null default is never null inside the module.

What conversion does

Terraform converts between similar types before it complains. The docs say it automatically converts number and bool to string when needed, and converts between similar complex types when it can. They also say it fails if any element is incompatible.

I wrote a small checker that follows those rules, to see the edges. It is my stand-in and not Terraform, so exact error wording differs:

'5'          as number: ok -> 5
5            as string: ok -> '5'
'yes'        as bool: ERROR 'yes' is not bool
'true'       as bool: ok -> True
['1', '2']   as ('list', 'number'): ok -> [1, 2]
['1', 'x']   as ('list', 'number'): ERROR 'x' is not number
object, port omitted : {'name': 'web', 'port': 8080, 'tls': False}
object, name omitted : ERROR attribute 'name' is required

The pattern: strings that look like the target convert, others do not, a list fails if any one element fails, and an object requires every non-optional attribute. The checker is crude on one point, because it ignores extra attributes passed to an object. In Terraform, extra attributes are dropped silently during conversion, to my understanding of the docs, but I did not verify that. Test it before you rely on it.

This leniency is useful and slightly dangerous. "false" becomes false quietly, so a value that came from an environment variable behaves as you hoped.

list, set or map: choosing

The choice shows up in the next lessons:

  • Use a list when order matters, such as an ordered set of rules. Beware that using a list with count ties each element to its position.
  • Use a set when you only care about membership. for_each accepts a set of strings, or a map, and not a list.
  • Use a map when elements have natural names, such as environment to CIDR. Map keys become stable resource addresses with for_each, which is better than positions.
  • Use an object when one thing has several named fields of different types, such as a service definition.
  • Use a map of objects for a collection of such things: map(object({...})). This is the shape that scales, because you add an entry to add a resource.

Count and for_each shows why that map-of-objects shape beats a list.

The any escape hatch

any is a placeholder for a type to be decided later. The docs are blunt: it is “very rarely the correct type constraint to use”, appropriate only if you pass the value directly on without looking inside. A module that inspects an any value has no checks on what it receives, and this is how wrong-shaped values slip through to a late error. If you find yourself typing any because the real type is long, write the long type. It is documentation for the next reader.

Combining with validation

Types check shape and validation checks meaning. A number could be -5, and a string could be "prodution". Put the type on, then add a validation block, like in the previous lesson, for what the type cannot say. Together they let a module reject nonsense at the door.

About the video

The embed is Tech Tutorials with Piyush’s “Day 7/28 - Terraform Type Constraints (simply explained)”, January 2025, starting at “Working with lists” (13:58) and running to the end at 42:21, about 28 minutes. Chapters cover lists, maps for tags, tuples and the element function, sets and object type constraints. It is long, and the earlier chapters on primitives and setup are skipped. Its chapters do not mention optional(), so that part is from the docs and changelog, not the video. English was judged from title, channel and English auto-captions. I judged content from chapter titles only.

Where this fits

You can describe what an input must look like. Next, make values depend on conditions and build new collections from old ones: conditionals and for expressions.

Check yourself

  1. 01What is the difference between `list(string)` and `set(string)` for something like subnet IDs?

    A list is ordered and allows duplicates. A set is unordered and unique. `for_each` needs a set or map, so a list must be converted with `toset()` first.

  2. 02A caller passes `port = "8080"` to a variable typed `number`. Does it fail?

    No. Terraform converts a numeric string to a number automatically. A string like `"http"` would fail, since it cannot be converted.

  3. 03How do you let callers omit `tls` from an object variable and default it to false?

    Declare it as `tls = optional(bool, false)` in the object type. Without a default an omitted optional attribute is null.

  4. 04Why is `type = any` a code smell for a module's inputs?

    It accepts anything, so mistakes surface deep inside the module instead of at the boundary. The docs say it is only appropriate when you pass the value straight through without inspecting it.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark