Back to Terraform

HCL Edge Cases: Null, Optional Objects and Collection Shape

November 6, 2026 Wasil Zafar 26 min read

Reason about type conversion and nested data without relying on trial-and-error expressions

Table of Contents

  1. Missing, Null and Empty Values Are Different Contracts
  2. Lists, Sets, Tuples, Maps and Objects Transform Differently
  3. Conditional Branches Must Produce Compatible Types
  4. Normalize External JSON or YAML at One Boundary
  5. Turn a Nested Data Model into Stable Resource Keys

Missing, Null and Empty Values Are Different Contracts

Three different events get called "no value" in review. A caller omits an attribute, a caller writes an explicit null, or a caller supplies an empty string or collection. Terraform resolves each at a different layer and at a different moment, so one module can accept the first, substitute for the second and still fail on the third.

Unset is an event at the type boundary, not a value. During conversion, absence has to be resolved: a required attribute errors, an optional attribute takes its default, and an optional attribute with no default becomes null. For an optional attribute, downstream expressions cannot distinguish "omitted" from "wrote null" — both arrive as the same typed value.

An explicit null does not opt out of a default. The documented guarantee is unusually strong: an optional attribute with a non-null default never has the value null inside the receiving module. Terraform substitutes the default both when the caller omits the attribute and when the caller sets it to null, so a defaulted port answers 8080 in either case.

Nullable guards the outer value, one level deep. Setting nullable = false rejects a whole variable set to null, and the error states that the required variable may not be set to null. It does not reach inside: a non-null object can still carry a null attribute, and conversion accepts it.

Missing, Null and Empty Values Are Different Contracts
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    A["Caller supplies an object"] --> B{"Attribute present in the literal?"}
    B -->|"no"| C{"optional() declared?"}
    C -->|"yes"| C1{"Default declared?"}
    C1 -->|"yes"| G["Default substituted
never null"] C1 -->|"no"| H["Typed null reaches expressions"] C -->|"no"| X["Error: required attribute
missing during conversion"] B -->|"yes"| D{"Value is null?"} D -->|"yes"| E{"optional() with a default?"} E -->|"yes"| G E -->|"no"| H D -->|"no"| F{"Empty string, list or map?"} F -->|"yes"| E1["Accepted as a value
length is zero"] F -->|"no"| V["Typed value reaches expressions"] A2["Whole variable set to null"] --> I{"nullable = false?"} I -->|"yes"| J["Error: required variable
may not be set to null"] I -->|"no"| K["null replaces the
variable-level default"] classDef primary fill:#132440,color:#ffffff,stroke:#0b172b; classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a; classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f; classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420; classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f; class A,A2 primary; class B,C,C1,D,E,F,I secondary; class E1,G,K,V ok; class J,X danger; class H warn;
Three null decisions at three boundaries A whole variable set to null hits the nullable guard and either errors or replaces the variable default. An omitted or null object attribute hits the optional default and becomes the default. An empty value passes conversion and is kept with length zero. The layer that owns the default decides what null means 1. whole-variable boundary service = null allowed by default nullable = false? outer value only error required variable null wins over the default 2. optional attribute boundary omitted or null inside the object optional default? conversion fills it default never null typed null no default declared 3. value boundary "" or [] or {} type conversion accepted: length is zero only a length rule rejects it Nothing downstream can tell an omitted attribute from an explicit null after conversion. An empty value is not a gap in the object; it is the caller's decision.
StateCaller writesModule receivesGuard that decides
Omitted attributeNothing for that keyThe default; null if optional without one; otherwise an errorA required attribute fails conversion
Explicit null with a defaultnullThe default, never nullNone needed; the rule is automatic
Explicit null without a defaultnullA typed nullHandle it, or declare a default
Whole variable nullnullAn error when nullable is false; otherwise null replaces the variable defaultnullable on the variable block
Empty value"", [] or {}The same value, with length zeroA length rule or a named condition
Unknown valueA value not known until apply(known after apply)A check block or a precondition

The variable level and the attribute level follow opposite null rules. With nullable left true, a whole variable set to null replaces its variable-level default with null. One level down, an attribute with a non-null optional default does the reverse and replaces null with the default. Same keyword, different owner, different result.

Do not use coalesce as a null test. It skips both null and the empty string, so an intentional "" is silently replaced by the fallback. If absence and emptiness mean different things, compare against null explicitly instead of letting a convenience function decide.

Decide by what the body can tolerate. If an attribute must exist, make it required. If a safe value exists, give it an optional default. If null is meaningful, leave the default off and handle it. Whichever you choose, emptiness still needs a length rule, because conversion will never reject it.

Lists, Sets, Tuples, Maps and Objects Transform Differently

A literal is narrower than the type you asked for. A bracketed literal such as ["a", 1] is a tuple with one type per position, and a brace literal is an object with one type per attribute. Declaring a list or a map asks Terraform to convert that value, and every surprise in this section happens inside that conversion.

Collections demand one element type; structural types do not. list, map and set each carry a single element type, so conversion has to find one type every element can become. tuple and object preserve per-position and per-attribute types, which is why a tuple can hold a string and a number while a list cannot.

Conversion is recursive, and it coerces primitives without asking. A number or bool becomes text when the target element type is string, so a map declared as map(string) turns the port 8080 into "8080". That is legal and silent, and it only hurts later when a provider schema wanted a number back.

Some conversions are lossy in both directions. Object to map keeps the keys but must unify the values, and a list-valued attribute cannot become text, so the whole conversion fails. Map to object keeps only the declared keys, and object to object discards attributes the schema does not mention, so a typo disappears rather than erroring.

Order and uniqueness are data, not formatting. Converting a list to a set removes duplicates and ordering; converting back gives arbitrary order, and for strings the console shows lexicographic order. A set is a membership contract, not a sequence that happens to be sorted.

Tuples are contracts about positions. A list converts to a tuple only when the lengths match exactly, and a tuple converts to a list only when every position unifies to one element type. [1, "a"] becomes a list of strings only because number-to-string conversion exists.

A map is not a record. map(string) promises that every value is text, so a record with a numeric port loses the number and the ability to give each field its own type. Reach for an object when the fields have different jobs, and for a map when the keys are data and the values are interchangeable.

A set of objects is not a set of strings. for_each accepts a set only when its elements are strings, and a set whose elements are objects fails even though the outer kind is right. The element type, not just the collection kind, decides whether a value can become an address.

Four conversions and what each one costs A tuple converts to a list of strings by coercing the number. A list converts to a set and loses duplicates and order. An object converts to a map of strings by coercing the port. An object containing a list fails to convert to a map of strings. The target kind decides which parts survive tuple(["a", 1]) types: string, number list(string) one element type ["a", "1"] number coerced, position lost ["a", "a", "b"] ordered, duplicates allowed set(string) unique, unordered {"a", "b"} duplicate and order lost object({name, port}) attribute types differ map(string) values must unify port = "8080" names kept, number coerced object({ports}) one value is a list map(string) no common type conversion fails cannot convert object to map Object to object also drops attributes the target schema does not declare. Map to object keeps declared keys and discards the rest, so a rename can look like a removal. The console is the fastest witness: ask for the type before and after the conversion.
Lists, Sets, Tuples, Maps and Objects Transform Differently
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    A["Source value from a literal or decode"] --> B{"Target is list, map or set?"}
    B -->|"yes"| C{"Every element or value unifies?"}
    C -->|"yes"| D["Convert recursively
coerce primitives"] C -->|"no"| E["cannot convert to
a single element type"] B -->|"no"| F{"Target is a tuple?"} F -->|"yes"| G{"Length matches exactly?"} G -->|"yes"| H["Convert each position"] G -->|"no"| I["tuple length mismatch"] F -->|"no"| J{"Target is an object?"} J -->|"yes"| K{"Every required attribute present?"} K -->|"yes"| L["Drop undeclared attributes"] K -->|"no"| M["missing required attribute"] D --> N{"Was the source ordered or unique?"} N -->|"set involved"| O["Order or duplicates lost"] N -->|"no"| P["Value keeps its shape"] classDef primary fill:#132440,color:#ffffff,stroke:#0b172b; classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a; classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f; classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420; classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f; class A,P primary; class B,C,F,G,J,K,N secondary; class D,H,L ok; class E,I,M danger; class O warn;

The console is the cheapest way to see the difference. Type the literal, ask for its type, then ask for the conversion and ask again. The first answer explains the failure; the second shows what the module will actually receive.

Conditional Branches Must Produce Compatible Types

A conditional chooses a value, never a type. Terraform fixes the result type before it evaluates the condition, so both arms must already share a type or convert to one common type. The condition then picks a value inside that decided type.

A shared type can be a promotion. true ? "yes" : 1 returns the string "yes", because every number converts to text. A list of numbers against a list of strings does the same element by element, so true ? [1] : ["a"] returns a list of strings with "1" in it.

Object arms unify to a map, not an object. When both arms are objects, the common type is a map whose values share one type. Keys are not intersected, but the result loses its object schema, so which keys exist depends on the winning branch.

Before: the branch changes the key set. The false arm has no spot key, so reading spot from the result fails on that path with "Missing map element". A map permits any string key, so the type checker cannot warn you in advance.

settings = var.environment == "prod" ? { size = "large", spot = true } : { size = "small" }

After: both arms have the same key set. Every key now exists on both paths, and the result can be consumed as an object with a stable schema.

settings = {
  size = var.environment == "prod" ? "large" : "small"
  spot = var.environment == "prod"
}

The silent case is a later conversion. If the conditional flows into an argument with a declared object type, conversion keeps only that schema's keys, so an extra setting disappears without an error. The conditional preserved it; the object conversion discarded it.

Incompatible kinds and attributes fail loudly. A tuple against a string stops the run with "Inconsistent conditional result types". Two objects that share an attribute with incompatible types fail with the same summary and name that attribute, which is better than a map whose keys depend on the branch.

Null is compatible with every type and means omission. An arm that returns null produces a typed null, and passing it to an optional resource argument leaves the argument unset. Use null for absence and an empty value for emptiness; a conditional should not blur the two.

An unknown condition does not skip the type check. Both arms are typed first, and the result becomes unknown until the condition is known. That unknown then propagates to whatever consumes the conditional, so a plan can defer a decision without ever relaxing the shape.

Conditional arms unify to one type before the condition runs The true and false arms feed a unification gate that produces one result type. Number and string promote to string. Tuple and string fail with inconsistent conditional result types. Two objects unify to a map whose values share a type, so the keys that exist follow the winning branch. Both arms are typed before the condition is evaluated true arm "yes" or 1 or [1] false arm "no" or "a" or ["a"] unify to one type convert both arms or stop the run result type decided once, then the condition selects a value number + string: promotes to string true ? "yes" : 1 returns "yes" tuple + string: no common type error: Inconsistent conditional result types object + object: no fixed schema keys depend on the winning branch A type error is recoverable. A key set that changes with the flag is harder to see.

The safe pattern is shape-first. Build a local that already has the full shape, give every attribute a value, and let the conditional choose only that value. When a branch genuinely needs a different shape, convert both arms explicitly and accept that the conversion, not the condition, owns the type.

Normalize External JSON or YAML at One Boundary

Decoders produce shape, not a schema. jsondecode and yamldecode map JSON and YAML onto Terraform values: objects become objects, arrays become tuples, and numbers become numbers. Nothing checks that keys exist, that types agree across entries, or that a list has one element type.

An array of unlike objects decodes as a tuple of unlike objects. That single fact explains most downstream failures: position zero may be one object type and position one another, so a conversion that assumes one element type has nothing to unify.

Normalizing means rebuilding, not casting. Pluck the fields you trust, coerce each one, and give every entry every key, so the result has one shape. Casting the decoded value with tomap() or tolist() works only when the raw data already agrees; it fails loudly when it does not.

Do the rebuild in one local and let everything downstream read that local. A boundary you can point at beats a try() repeated in every resource argument, because the shape is decided once and the rest of the module reads a stable type.

Validate after shaping, not during decoding. A variable validation can only see its own variable, so rules over decoded data belong in a check block or a resource precondition. A check block reports a warning and continues; a precondition stops the plan.

Configuration

Normalize External JSON or YAML at One Boundary

Execution status: design-only. The configuration is valid for Terraform CLI 1.17.1, but this article does not claim the commands were run. There is no provider and nothing billable.

Prerequisites. Terraform CLI 1.17.1, an empty scratch directory, and a shell. No credentials and no network access beyond the binary.

Create services.json with two entries that disagree on purpose. One carries tags, the other carries replicas, and one port is quoted:

[
  { "name": "api", "port": 8080, "tags": { "env": "prod" } },
  { "name": "web", "port": "9090", "replicas": 2 }
]

Create main.tf with one decode, one rebuild and one check:

locals {
  decoded = jsondecode(file("${path.module}/services.json"))

  services = {
    for s in local.decoded : s.name => {
      port     = tonumber(s.port)
      replicas = try(tonumber(s.replicas), 1)
      tags     = try({ for k, v in s.tags : k => tostring(v) }, {})
    }
  }
}

output "services" {
  value = local.services
}

check "service_ports" {
  assert {
    condition     = alltrue([for name, s in local.services : s.port > 0 && s.port <= 65535])
    error_message = "Every service port must be from 1 to 65535."
  }
}
  1. Run terraform init -input=false, then terraform console. No provider should be installed.
  2. Ask type(local.decoded). Expect a tuple of two different object types: the first has name, port and tags with a number port, the second has name, port and replicas with a string port.
  3. Ask tomap(local.decoded). Expect the error "cannot convert tuple to map of any single type." The data is not wrong; the shape is a tuple and the values do not unify.
  4. Ask local.services. Expect two entries with the same three keys, port as a number, replicas defaulted to 1 for api, and tags defaulted to an empty map for web.
  5. Change the web port to 70000 and run terraform plan -input=false. Expect the output values plus "Check block assertion failed", and the plan still completes. Change it back.

Expected observation. One decode produces a tuple with two incompatible object types. The rebuild produces one uniform shape, so every downstream expression can assume the same three attributes.

Failure check. If tomap succeeds, the entries already share one object type and the lesson is invisible; make the entries differ again. If the check block stops the plan, it was written as a precondition, not a check.

Cost and cleanup. Zero. The lab installs no provider, creates no resource and writes no state. Delete the directory when finished.

One decode, one rebuild, one stable shape A JSON array decodes to a tuple of two different object types. The rebuild local coerces each field and supplies every key, producing a uniform map of objects that for_each can consume. Casting the raw tuple with tomap fails before the rebuild. Decode at the edge, rebuild once, publish one type services.json entry 1: name, port, tags entry 2: plus replicas port is number, then string normalize local tonumber(port) try(replicas, 1) try(tags, empty map) one uniform shape port: number replicas: number tags: map(string) tomap(local.decoded) skips the rebuild cannot convert tuple to map of any single type The tuple is a faithful decode. It is not a schema, and casting cannot make it one. A check block reports a bad value and keeps going; a precondition blocks the plan. Downstream expressions should read the rebuilt local, never the raw decode.

A normalized local is also a review artifact. Its keys are the fields the module actually consumes, so a field the provider added to the JSON does not silently travel further. When the upstream format changes, only that one expression needs an edit, and the console shows the new shape immediately.

Turn a Nested Data Model into Stable Resource Keys

A key is an address, not a label. for_each turns each map key into part of the instance address, so renaming a key destroys the old instance and creates a new one unless a moved block says otherwise. Key stability therefore matters more than the elegance of the expression that builds the key.

The result kind follows the source shape. A keyed for expression produces an object with one attribute per key, and tomap() turns that object into a map when a consumer insists on one. Keys are always strings; positions are not keys, even when they print as numbers.

for_each accepts a map or a set of strings, never a list. Handing it a list fails before anything is planned, with a diagnostic that names the list type it received. That error is a feature: a list would make the instance key depend on ordering. A key that is unknown until apply is rejected for the same reason, because the address must exist when the plan is built.

Heterogeneous values pass the key check and fail in the body. An object whose entries have different attributes is still a legal for_each value, because only the keys are inspected. The failure arrives later, when the block reads an attribute that one entry lacks, and the message says the object has one attribute and no such name.

Duplicate keys are a hard error, not last-write-wins. The for expression reports "Duplicate object key" and names the repeated value, which is what you want before two instances collide. If duplicates are genuinely valid, the ellipsis grouping form is a deliberate choice rather than an accident.

Index keys are the tidy-looking anti-pattern. Keys "0" and "1" survive an append but shift when an entry is removed or reordered, so every later entry changes address. A name key moves only the resource whose name changed.

Declare the element type once and the rest follows. A list of objects with optional() defaults converts to a uniform list, a keyed for expression over it produces uniform values, and for_each can read every attribute on every entry.

Renaming a key is a migration, not a refactor. A moved block maps the old address to the new one, and without it the same edit appears as a destroy plus a create. Add the moved block in the change that renames the key, not in a later cleanup, so the history stays readable.

Lab

Repair a data-shape defect

Execution status: design-only. The worksheet targets Terraform CLI 1.17.1 and uses only the console and built-in values. Nothing is applied and no provider is downloaded.

Prerequisites. Terraform CLI 1.17.1, an empty directory, and a shell.

Start with the shape you wish the data had, not the shape it arrived in:

variable "services" {
  type = list(object({
    name     = string
    port     = optional(number, 8080)
    replicas = optional(number, 1)
  }))
  default = [
    { name = "api", port = 9090 },
    { name = "web" },
  ]
}

locals {
  keyed   = { for s in var.services : s.name => s }
  byindex = { for i, s in var.services : i => s.name }
}
Question to askExpressionExpected answerWhat it proves
What type arrived?type(var.services)list of object with name, port, replicasThe variable converted the default
What did the defaults fill?var.servicesapi port 9090, web port 8080, replicas 1Optional defaults are complete
What shape did keys produce?type(local.keyed)object with api and web attributesA keyed for yields an object
What does for_each prefer?type(tomap(local.keyed))map of objectOne stable element type

A shape the variable would have repaired. The same keyed expression over a hand-written tuple keeps the two entries as different object types:

locals {
  uneven = {
    for s in [{ name = "api", port = 8080 }, { name = "web" }] : s.name => s
  }
}
  1. Run terraform console in the directory. Ask each question in the table and compare the printed type with the expected one.
  2. Ask local.byindex. Expect keys "0" and "1"; then swap the two default entries and ask again. The keys now point at the other service, which is the address change a plan would show as a replacement.
  3. Add a third entry with the same name, "api", and ask for local.keyed. Expect "Duplicate object key" and a message naming "api" as the repeated value. Remove it.
  4. Change the variable to type = list(object({ name = string, port = number })) in a scratch copy and delete the port from the web entry. Expect a conversion error naming the missing attribute, not a null.
  5. Point a terraform_data resource at for_each = local.keyed and set input = each.value.port. Expect addresses ["api"] and ["web"], and both ports readable because the element type is uniform.
  6. Point the same resource at the uneven map and read the port. Expect the api instance to plan and the plan to reach "Unsupported attribute" for web, because that entry has only a name.

Expected observation. The declared element type is the repair: it supplies defaults, makes every keyed value identical in shape, and lets the body read any attribute without a per-entry guard.

Failure check. If local.byindex keys stay attached to the same service after a reorder, the expression was not index-based. If the duplicate entry is accepted, the map is being built with grouping enabled. If for_each accepts a list, the argument is not the one you think it is.

Cost and cleanup. Zero. No provider, no state and no remote object; delete the directory when finished.

The repair generalizes beyond this example. Whenever a nested list becomes a keyed map, ask three questions: which field is unique and human-readable, does every entry have the same attributes, and does the body read only those attributes? A yes to all three gives you an address that survives edits and a plan that changes only what the caller changed.