Objective 4 of the Terraform Associate (004) exam, Terraform configuration, contains the sub-objective most candidates underestimate: 4d, “Understand and use complex types.” Our variables, outputs and locals guide shows the three type families and the one-paragraph version of conversion: Terraform coerces compatible types automatically and fails on invalid ones. The functions and expressions guide covers try, lookup and coalesce for missing values, and the ephemeral values guide covers keeping secrets out of state.
The exam goes a layer deeper. It asks why a module that declares list(string) happily accepts a tuple literal but == against [] is always false. It asks what optional(string, "x") does when the caller passes null explicitly. It asks which of ["a", 1] and ["a", []] satisfies list(any). It asks when nonsensitive is legitimate, why the sensitive flag does not protect state, and what tostring(null) returns. Those are type-system questions, and they are answerable from a small set of rules.
This guide is a practitioner’s walk through those rules, written for the Terraform Associate exam and verified against the current HashiCorp documentation. The exam is pinned to Terraform 1.12; the current release is 1.17.2 (11 November 2026). Where a feature arrived after 1.12 (the convert function, const and deprecated in 1.15) it is marked, because you will meet it in real code but not in a question.
The Three Type Families
Terraform has three primitive types, three collection type kinds and two structural type kinds, plus null.
| Family | Types | Rule that defines it |
|---|---|---|
| Primitive | string, number, bool | A single value. number covers whole and fractional values (15, 6.283185). |
| Collection | list(T), map(T), set(T) | ”All elements of a collection must always be of the same type.” Lists are indexed from zero, maps by string label, sets are “unique values that do not have any secondary identifiers or ordering”. |
| Structural | object({...}), tuple([...]) | Each element has its own type: an object has named attributes with individual types, a tuple has an ordered sequence of per-position types and “must have exactly the same number of elements”. |
| Absence | null | ”A value that represents absence or omission.” It has no type of its own. |
The reason the exam keeps returning to this table is a sentence from the Types and Values page: “In most situations, lists and tuples behave identically, as do maps and objects.” A literal written in square brackets is a tuple (each element may have a different type); a literal in braces is an object. Terraform converts them to a list or map when a type constraint asks for one. So ["a", "b"] is a tuple of two strings until it meets type = list(string), at which point it becomes a list(string). The distinction surfaces in exactly three places: the type() console function, error messages about “inconsistent types”, and the conversion rules below.
Two literal-syntax facts also recur. Map keys may be unquoted when they are valid identifiers and must be quoted “when a key starts with a number, contains spaces, or contains special characters”; a non-literal key goes in parentheses, as in (var.tag_name) = "SRE". And terraform fmt accepts colons as key-value delimiters but leaves them alone, which is why a JSON-shaped object literal is valid HCL.
Indexing and the set exception
Lists and tuples index with whole numbers, maps and objects with strings or dot notation for identifier-shaped keys. Sets cannot be indexed at all: “Sets cannot be indexed directly because they are unordered.” Convert with tolist first, or iterate with for_each, which is the route the count vs for_each guide explains.
Why list vs set vs map Matters for for_each
The one place where the family you choose changes a plan is for_each, which accepts a set of strings or a map, never a list. The practical pattern is for_each = toset(var.names) for a list input. The reason the exam prefers sets and maps there is that they key instances by value rather than position, so inserting an element in the middle does not renumber every resource. That is the count vs for_each guide’s territory; here the relevant type facts are that toset deduplicates and loses ordering, and that when a set is converted back to a list “the order is arbitrary” except that sets of strings sort lexicographically.
optional() Attributes: The Exact Rules
Object type constraints in module inputs originally required callers to supply every attribute. Terraform 1.3 (21 September 2022) made the optional modifier stable and added its default argument: “you can now declare individual attributes as optional, and specify a default value to use if the caller doesn’t set it.” That release also “concludes the module_variable_optional_attrs experiment” and removed the experimental defaults() function. If a question offers defaults() as an answer, it is a trap.
variable "service" {
type = object({
name = string
port = optional(number, 8080)
public = optional(bool) # null when omitted
labels = optional(map(string), {})
health = optional(object({
path = optional(string, "/healthz")
interval = optional(number, 30)
}), {})
})
}
Rules, each of which has appeared in a scenario:
optional(TYPE)with no default yieldsnullwhen omitted. Your module must handle the null (var.service.public == null ? false : var.service.public, orcoalesce).optional(TYPE, DEFAULT)is guaranteed non-null inside the module. The docs: the attribute is “guaranteed to never have the valuenullwithin the receiving module”, and Terraform “substitutes the default both when the attribute is omitted and when it is explicitly set tonull”. So a caller passingport = nullstill gets 8080. This is the opposite of a top-level variable withnullable = true, where an explicitnulloverrides the default.- Nested defaults apply top-down. In the example, if the caller omits
healthentirely, Terraform first applies the outer default ({}), then applies the nested defaults inside it, producingpath = "/healthz"andinterval = 30. If the caller passeshealth = { interval = 10 }, onlypathis defaulted. - A default is applied during conversion, not at evaluation time. The result is a fully-populated object of the declared type, which is why the module can reference
var.service.health.pathwithout conditionals. optionalis valid only insideobject({...})type constraints for input variables (and, since outputs gained type constraints, in output types). It is not a standalone type and cannot wrap a whole variable; a top-level optional variable is one with adefault.- Extra attributes are discarded. When a value is converted to an object type, “the extra attributes are discarded during type conversion”. A caller who misspells
lablesgets no error from the type system; a validation rule or apreconditionis how you catch it.
Module authors use this to build stable interfaces: callers write only what they need, the module reads a complete, typed object, and the object type documents the contract in a way map(any) never can.
The any Placeholder and How It Is Resolved
any is not a type. The docs: it “is a placeholder, not a type”. When Terraform sees list(any) it “looks for a single concrete type that can replace it and makes the whole value valid”. The three documented cases are the exam’s three answer options:
Value passed to list(any) | Resolved type | Result |
|---|---|---|
["a", "b", "c"] | list(string) | unchanged |
["a", 1, "b"] | list(string) | ["a", "1", "b"] (the number is converted to a string because that is the one type all elements can become) |
["a", [], "b"] | none | error: no single type fits a string and a tuple |
The same principle “applies to map(any) and set(any)”. A bare list, map or set keyword is shorthand for list(any) and so on. And the docs carry a warning the exam has turned into a best-practice question: “Do not use any just to avoid specifying a type constraint.” Use it “only when data is passed through opaquely”, such as a value handed straight to jsonencode. Otherwise you lose validation, documentation and the ability to detect a caller’s mistake. type = any on its own accepts anything, including structural values, and defers all checking to wherever the value is used.
The Conversion Rules
Terraform “converts types automatically where possible” and “raises a type mismatch error” otherwise. The rules split into primitive and complex.
Primitive conversions
numberandboolconvert tostringfreely:15becomes"15",truebecomes"true".- A
stringconverts tonumberorbool“only if the string contains a valid representation of a number or bool value”:"15"to15,"true"totrue, but"yes"or"abc"fail. boolnever converts tonumberand vice versa.tobool(1)fails with “cannot convert number to bool”.
Complex conversions
| From | To | Allowed when | Loss |
|---|---|---|---|
| tuple | list | Elements can all convert to one type | none (becomes homogeneous) |
| list | tuple | The list has “exactly the required number of elements” | none |
| object | map | Attribute values can all convert to one type | none |
| map | object | The map has at least the required keys | extra attributes dropped, so map to object to map is lossy |
| list or tuple | set | Always | duplicates discarded, ordering lost |
| set | list or tuple | Always | order “arbitrary”; strings come out lexicographically sorted, other types in no guaranteed order |
| tuple or list | string | Never | error: “a tuple cannot be converted to a string” |
Conversion is recursive: Terraform converts the elements, applying the primitive rules to leaves. That is how ["a", 1] becomes ["a", "1"] for list(string).
The equality trap
One operator refuses to convert. The Operators page: “the equality operators require both arguments to be of exactly the same type in order to decide equality”, so a == b “returns true if a and b both have the same type and the same value”. Consequences the exam loves:
"1" == 1isfalse. Convert first withtonumberortostring.var.list == []wherevar.listislist(string)is always false, because[]is an empty tuple andvar.listis a list. The docs call this out by name: the two values “can never match”. Uselength(var.list) == 0instead.- The same applies to
var.map == {}(an empty object vs a map).
Arithmetic and comparison operators do convert: they “expect number values” and Terraform “will attempt to convert values to the required type automatically”, so "2" + 3 is 5. Logical operators expect bools. Precedence from highest to lowest is ! and unary -; then *, /, %; then + and binary -; then >, >=, <, <=; then == and !=; then &&; then ||. There is no exclusive-or operator.
null and nullable
null means “absence or omission”. Setting a resource argument to null makes Terraform “behave as though the argument was omitted”: the provider’s default applies if there is one, and a required argument errors. That makes null the tool for conditionally omitting arguments: kms_key_id = var.encrypt ? var.key : null.
For input variables, the nullable argument (default true) governs whether a caller may pass null:
- With
nullable = trueand adefault, a caller can “explicitly set the variable value to null, overwriting the default argument”. The module then has to handle a null. - With
nullable = false, “that variable must have a value that is not null”. Passingnullis rejected rather than silently replaced, so the module can rely on the value. Nulls inside a collection or structure are still allowed “as long as the collection or structure itself is not null”.
Contrast this with optional(TYPE, DEFAULT) inside an object, where an explicit null is replaced by the default. The exam sometimes pairs the two to check that you know which one substitutes and which one rejects.
Two more variable-block facts belong here. The default “requires a literal value and cannot reference other objects in the configuration”, and “the default value must convert to the specified type”, which is the one place the type constraint is checked at declaration time. And the reserved names you cannot use for a variable are source, version, providers, count, for_each, lifecycle, depends_on and locals.
Passing Complex Values In
Values assigned from outside are converted to the declared type on the way in, and the precedence order (highest first) is -var and -var-file in command-line order plus HCP Terraform variables, then *.auto.tfvars and *.auto.tfvars.json in lexical order, then terraform.tfvars.json, then terraform.tfvars, then TF_VAR_ environment variables, then the default. “Once you assign a value to a variable, you cannot reassign that variable within the same file.”
For complex values the syntax question is a favourite: on the command line and in environment variables you write the value in HCL expression syntax, for example -var='subnet_ids=["subnet-12345","subnet-67890"]' and export TF_VAR_config='{"key": "value", "list": ["a", "b"]}'. The JSON look of the second example is still HCL (quoted keys and colons are valid), which is why the docs can call it “proper JSON syntax” without contradiction. Because shell quoting is painful, the docs recommend “setting complex variable values with variable definition files”. Undeclared variables are ignored in the environment, warned about in .tfvars files, and are an error with -var.
The Explicit Conversion Functions
“Explicit type conversions are rarely necessary in Terraform because it will convert types automatically where required.” The docs’ guidance is to “use the explicit type conversion functions only to normalize types returned in module outputs”, so that a module’s interface has a stable, documented type rather than whatever a provider happened to return.
| Function | Accepts | Rejects | Example from the docs |
|---|---|---|---|
tostring | primitives and null | anything else: tostring([]) fails with “cannot convert tuple to string” | tostring(true) is "true"; tostring(null) is a null of type string |
tonumber | numbers, decimal strings, null | tonumber("no"): “string must be a decimal representation of a number” | tonumber("1") is 1 |
tobool | true, false, the exact strings "true" and "false", null | tobool("no"): “only the strings “true” or “false” are allowed”; tobool(1): “cannot convert number to bool” | tobool("true") is true |
tolist | any list, tuple or set | heterogeneous values that cannot unify | tolist(["a", "b", 3]) is ["a", "b", "3"]; a set gives “an undefined order that will be consistent within a particular run” |
toset | any list, tuple or set | likewise | toset(["c", "b", "b"]) is ["b", "c"]; toset(["a", "b", 3]) is ["3", "a", "b"] |
tomap | any map or object | likewise | tomap({"a" = "foo", "b" = true}) is {"a" = "foo", "b" = "true"} |
Three exam points fall out of that table. First, the collection functions convert mixed elements “to the most general type”, which in practice means string. Second, null passes through every conversion function as a typed null. Third, a tuple of two elements converts to list(string), but tostring of a tuple does not: structural-to-primitive is never allowed.
convert(value, type) and type()
Terraform 1.15 (April 2026, after the exam’s pinned version) added convert, which “evaluates an expression from the first argument, and converts the resulting value to the type constraint from the second argument”, using “the same type expressions as variable and output type parameters”. It applies optional() defaults during conversion and, importantly, lets you create empty typed containers: convert([], list(string)) is an empty list of strings rather than an untyped empty tuple, which solves the var.list == [] class of problem at the source. The docs now describe tolist, toset and tomap as equivalent to convert with list(any), set(any) and map(any), and recommend convert “to specify a more precise type” when the any inference would be ambiguous. Treat convert as real-world knowledge, not an exam answer.
type() is older (Terraform 1.0) and “is only available in the terraform console command”. It “returns the type of a given value” and is the fastest way to see why Terraform calls your literal a tuple rather than a list:
> type(["a", "b"])
tuple([
string,
string,
])
> type(tolist(["a", "b"]))
list(string)
> type({ name = "x", port = 80 })
object({
name: string,
port: number,
})
The docs add that type “should not be used in more complex expressions”; it is a diagnostic, not a building block.
try and can at Validation Altitude
The functions guide covers try as a missing-value tool. Two type-system details sit on top of that.
try(...) “returns the result of the first one that does not produce any errors”, but it “can only catch and handle dynamic errors resulting from access to data that isn’t known until runtime” and “will not catch errors relating to expressions that can be proven to be invalid for any input”. A reference to an undeclared local is a static error and still fails inside try. The docs also warn that “overuse of try to suppress errors will lead to a configuration that is hard to understand and maintain” and suggest confining it to “special local values whose expressions perform normalization” of external data such as decoded JSON or YAML:
locals {
raw = yamldecode(file("${path.module}/config.yaml"))
normalized = {
name = tostring(try(local.raw.name, null))
groups = try(local.raw.groups, [])
}
}
can(...) “returns a boolean value indicating whether the expression produced a result without any errors”, and “the primary purpose of can is to turn an error condition into a boolean validation result when writing variable validation”. The documented example checks a timestamp; the equivalent for a regex is the pattern you will see in questions:
variable "cidr" {
type = string
validation {
condition = can(cidrhost(var.cidr, 0))
error_message = "cidr must be a valid IPv4 or IPv6 CIDR block."
}
}
variable "image_id" {
type = string
validation {
condition = can(regex("^ami-[0-9a-f]{8,17}$", var.image_id))
error_message = "image_id must look like an AMI ID."
}
}
Validation facts the exam checks: condition and error_message are both required; “Terraform evaluates variable validations while it creates a plan”; a false condition “raises an error showing error_message and stops the operation”; a variable may have several validation blocks; and since Terraform 1.9 (June 2024) “input variable validation rules can now refer to other objects in the same module”, so a condition can compare one variable against another or against a data source. The pre-1.9 rule that a condition may reference only its own variable still appears in older study material; the 1.12-pinned exam is on the newer side of that line. The error_message “supports any expression that evaluates to a string”, so interpolating the offending value is fine. For the related precondition, postcondition and check blocks, see the check blocks guide.
sensitive: Propagation, Redaction and the Three Functions
Objective 4h asks you to “understand best practices for managing sensitive data”. The type system’s part of that is the sensitive mark, which rides on a value like a type attribute.
Marking a variable sensitive = true makes Terraform redact it in plan and apply output, and “Terraform also treats any expressions that use a sensitive variable as sensitive”. The mark propagates through interpolation, functions and resource attributes. What it does not do is the exam’s favourite distinction: “Terraform still records sensitive values in state”, state is “a plaintext file”, and terraform output -json and -raw display sensitive values in plain text. Protection for state is remote storage, encryption at rest and access control, which the state management guide covers; keeping a value out of state entirely is what ephemeral values and write-only arguments are for.
An output whose value is sensitive must itself be declared sensitive = true or the plan fails with an error telling you the output refers to sensitive values. In a child module, a sensitive output stays sensitive when the parent references it.
Three functions manipulate the mark:
| Function | Since | Does | Documented guidance |
|---|---|---|---|
sensitive(v) | 0.15 | Returns a copy of v marked sensitive | ”Wherever possible we recommend marking your input variable and/or output value declarations as sensitive directly”; the niche case is a value read inside the module, such as sensitive(file("secret.txt")), and even then the docs advise against shipping secrets in module files |
nonsensitive(v) | 0.15 | Returns a copy with the mark removed | Use “only when you’ve derived a new value from a sensitive value” that no longer contains the secret, for example nonsensitive(sha256(var.password)) or the non-secret username field decoded from a sensitive JSON blob; calling it on a value that is not sensitive produces the error “the given value is not sensitive, so this call is redundant”; misuse “is a bug in your module and not a bug in Terraform itself” |
issensitive(v) | 1.8 | Returns true if v carries the mark | issensitive(sensitive("secret")) is true, issensitive("hello") is false; useful in module logic that must branch on sensitivity without exposing the value |
The documented nonsensitive example is worth memorising because it is exactly how a scenario is worded: a variable holds a sensitive JSON string with a username and password; the module does jsondecode, which is sensitive as a whole; it then exposes nonsensitive(local.mixed["username"]) because the author knows that field is not secret, while the password stays marked. Calling nonsensitive on the whole decoded map would leak the password, and the docs say so.
ephemeral and ephemeralasnull
Terraform 1.10 added ephemeral values, which “omit the variable from state and plan files” entirely. An ephemeral variable may be referenced only in specific contexts: another variable or an output marked ephemeral (outputs only in child modules, never the root), a write-only resource argument, an ephemeral resource block, a provider block, and provisioner and connection configuration. Anything derived from an ephemeral value “implicitly becomes ephemeral”. The ephemeral values guide covers the resources and write-only arguments; the type-system piece is the function that bridges the two worlds.
ephemeralasnull(v) “accepts an ephemeral value and returns null” and, for a structure that mixes ephemeral and non-ephemeral attributes, “nullifies any ephemeral values within that object” while preserving the rest. The documented use is an output: merge a configuration map with an ephemeral session token, then ephemeralasnull(local.merged) in a non-ephemeral output so the environment name comes through and the token appears as a typed null. Without it, the output would have to be ephemeral and therefore unavailable in the root module.
Ephemeral and sensitive are independent marks: a value can be both, and sensitive without ephemeral still lands in state.
Version Timeline the Exam Cares About
| Version | Date | Type-system change |
|---|---|---|
| 0.13 | 2020 | validation blocks on variables |
| 0.15 | 2021 | sensitive() and nonsensitive() functions |
| 1.0 | 2021 | type() console function |
| 1.3 | Sept 2022 | optional(TYPE, DEFAULT) stable; experiment and defaults() removed |
| 1.8 | 2024 | issensitive() |
| 1.9 | June 2024 | Validation conditions may reference other variables, locals, data sources and resources |
| 1.10 | 2024 | ephemeral variables and outputs, ephemeralasnull() |
| 1.12 | 2025 | Version the 004 exam tests on |
| 1.15 | April 2026 | convert() function, const variables usable in module source/version, deprecated on variables and outputs, explicit type constraints on outputs |
| 1.17.2 | Nov 2026 | Current release; variables and locals allowed in provider requirements |
A question that mentions convert, const or deprecated is testing whether you know they are newer than the exam’s version; a question about optional defaults, nonsensitive or cross-variable validation is fair game.
Exam Cue to Answer Table
| Scenario wording | Answer |
|---|---|
| ”Module should accept an object where most attributes may be omitted” | object({...}) with optional(TYPE, DEFAULT) attributes |
”Caller passed null for an optional attribute with a default; what does the module see?” | The default; explicit null is replaced inside optional(TYPE, DEFAULT) |
”Caller passed null for a top-level variable with nullable = true and a default” | null; it overrides the default |
| ”Variable must never be null” | nullable = false |
”["a", 1, "b"] against list(any)” | Resolves to list(string), value ["a", "1", "b"] |
”["a", [], "b"] against list(any)” | Error; no single element type |
”var.list == [] is never true” | Empty literal is a tuple, list is not a tuple, == does not convert; use length(var.list) == 0 |
”"1" == 1” | false |
”Convert a list with duplicates for for_each” | toset(var.list); duplicates and order are lost |
| ”Index into a set” | Not possible; tolist first |
”tostring(["a"])” | Error: tuple cannot convert to string |
”tobool("yes")” | Error: only "true" and "false" |
| ”Map passed to an object type with extra keys” | Accepted; extra attributes silently dropped |
”Three-element list passed to tuple([string, number])” | Error; tuple requires exactly two elements |
”Why does terraform console say tuple for my list literal?” | Literals are tuples/objects until a constraint converts them; type() shows the literal’s type |
| ”Validate a variable’s format without crashing the plan” | can(regex(...)) or can(cidrhost(...)) in a validation block |
| ”Validation needs to compare two variables” | Allowed since 1.9 |
| ”Hide a password in CLI output” | sensitive = true; it is still in state |
| ”Output a hash of a sensitive value” | nonsensitive(sha256(var.secret)) with a comment explaining why |
| ”Output a non-secret field from a sensitive JSON variable” | nonsensitive(local.decoded["username"]); never the whole map |
”nonsensitive("literal")” | Error: value is not sensitive, call is redundant |
| ”Branch on whether a value is sensitive” | issensitive(v) (1.8) |
| “Keep a token out of state entirely” | ephemeral = true plus ephemeral or write-only consumers |
| ”Output a map that contains an ephemeral token from the root module” | ephemeralasnull(local.map); token becomes null, other fields survive |
| ”Create an empty typed list” | convert([], list(string)) in 1.15+; older code uses tolist([]) or a typed variable default |
”Use defaults() for optional attributes” | Removed in 1.3; use optional(TYPE, DEFAULT) |
Common Mistakes
Reaching for any to silence a type error. The docs tell you not to. A module with type = any cannot be validated, documented or safely refactored. Declare the object shape and use optional.
Expecting == to coerce. It is the one operator that never converts. Compare lengths for emptiness and convert strings to numbers explicitly.
Confusing the two null behaviours. Inside an object, optional(TYPE, DEFAULT) replaces an explicit null with the default. At the top level, nullable = true lets null override the default and nullable = false rejects it.
Treating sensitive as encryption. It redacts CLI output and propagates through expressions. State and terraform output -json still contain the plain value. Use remote encrypted state and, for values that must never be stored, ephemeral variables or write-only arguments.
Using nonsensitive to make the plan readable. Every call is a deliberate declassification. Use it only on a value you have proven no longer contains the secret, and leave a comment.
Assuming a set keeps its order. toset drops duplicates and ordering; converting back gives an arbitrary (strings: lexicographic) order.
Expecting an error for extra object attributes. Conversion discards them silently. Catch typos with validation or by making the attribute required.
Using try to hide a static error. It catches only dynamic errors such as a missing attribute on decoded data, not references to things that do not exist in the configuration.
Hands-On Lab: Make the Rules Visible in terraform console
No cloud account is needed; terraform console evaluates expressions locally. Create a directory with a single main.tf.
-
Declare a variable with optional attributes.
variable "svc" { type = object({ name = string port = optional(number, 8080) public = optional(bool) health = optional(object({ path = optional(string, "/healthz") interval = optional(number, 30) }), {}) }) default = { name = "api" } } variable "secret_json" { type = string sensitive = true default = "{\"username\":\"app\",\"password\":\"hunter2\"}" } locals { creds = jsondecode(var.secret_json) } -
Inspect the defaults. Run
terraform consoleand evaluatevar.svc. Confirmportis8080,publicisnullandhealthis fully populated from nested defaults. Then evaluatetype(var.svc). -
Prove the explicit-null rule. Change the default to
{ name = "api", port = null }, re-enter the console and evaluatevar.svc.port. It is still8080. -
Watch
anyunify. Evaluatetolist(["a", 1, "b"])andtype(["a", 1, "b"]). The first is alist(string), the second is a heterogeneoustuple. Then trytolist(["a", [], "b"])and read the error. -
Trip the equality trap. Evaluate
tolist([]) == [],[] == [],"1" == 1andlength(tolist([])) == 0. The second and fourth aretrue; the first and third arefalse, and the reasons are in the conversion section. -
Convert sets. Evaluate
toset(["c", "b", "b"]), thentolist(toset(["c", "b", "b"]))[0], then trytoset(["c", "b"])[0]and read the error about indexing a set. -
Exercise the sensitive mark. Evaluate
local.creds(redacted),issensitive(local.creds)(true),nonsensitive(local.creds["username"])(plain text) andnonsensitive("hello")(error). Then evaluatenonsensitive(local.creds)and notice that the whole secret appears; that is the misuse the docs warn about. -
Try the conversion functions. Evaluate
tostring(null),tonumber("1.5"),tobool("True")(note the capital T fails),tostring(["a"])and, if you are on 1.15 or later,convert([], list(string))followed byconvert([], list(string)) == tolist([]).
Twenty minutes in the console does more for Objective 4d than any amount of reading, because every rule above produces either a value or a diagnostic you will recognise on the exam.
Practice the Rules Until They Are Reflexes
The Terraform Associate does not ask you to recite the type lattice. It shows you a variable declaration and a value and asks what Terraform does, or shows you a failing expression and asks why. Each of those questions is one rule from this guide: literals are tuples and objects until converted, any must unify to one type, == never converts, optional defaults replace explicit nulls while nullable governs the top level, the to* functions only normalise, and the sensitive mark hides output but not state.
The fastest way to make those rules automatic is to run the console lab above and then pressure-test the reflexes against realistic distractors. Sailor.sh’s HashiCorp Terraform Associate Mock Exam Bundle includes eight 60-question exams whose explanations spell out why the defaults() answer, the nonsensitive-everything answer or the var.list == [] answer loses to the one Terraform actually implements. Pair this guide with the variables, outputs and locals guide for declaration syntax and precedence, the modules guide for how typed interfaces travel between modules, the Terraform Associate exam guide and the 30-day study plan, then test yourself on the Terraform Associate practice questions before booking.
Frequently Asked Questions
What is the difference between a list and a tuple in Terraform?
A list is a collection type: every element shares one type, written list(string). A tuple is a structural type: each position has its own type, written tuple([string, number]). A literal in square brackets is always a tuple; Terraform converts it to a list when a type constraint asks for one and the elements can unify to a single type. In most situations they behave identically, which is why the docs use the terms interchangeably, but the difference shows up in the type() function, in error messages about inconsistent types, and in the equality operator, where an empty tuple literal never equals a list.
What does optional(TYPE, DEFAULT) do if the caller passes null explicitly?
Terraform substitutes the default. The documentation guarantees the attribute “will never have the value null within the receiving module” whether the caller omits it or sets it to null. This differs from a top-level variable with nullable = true, where an explicit null overrides the default and the module receives null.
Why is var.list == [] always false?
Because the equality operators require both operands to be exactly the same type and never perform automatic conversion. [] is an empty tuple literal; var.list is a list. Different types mean the comparison is false regardless of contents. Use length(var.list) == 0, or in Terraform 1.15 and later compare against convert([], list(string)).
When is it acceptable to use the nonsensitive function?
Only when you have derived a new value from a sensitive value in a way that removes the sensitive parts, such as a hash of a password or a non-secret field decoded from a sensitive JSON blob. The docs say to use it “sparingly and only with due care”, to add a comment explaining why the call is safe, and that any leak caused by an inappropriate call is a bug in your module. Calling it on a value that is not sensitive produces an error.
Does marking a variable sensitive keep it out of the state file?
No. Terraform redacts sensitive values in plan and apply output and marks derived expressions sensitive, but “Terraform still records sensitive values in state”, and terraform output -json shows them in plain text. To keep a value out of state and plan files entirely, declare it ephemeral (Terraform 1.10 and later) and consume it only in ephemeral contexts or write-only arguments.
Which Terraform version does the Associate (004) exam test on?
The HashiCorp exam review page states the exam “Tests on Terraform version 1.12”. Features introduced in 1.15, such as the convert function, const variables and the deprecated argument, are not in scope, while optional defaults (1.3), issensitive (1.8), cross-variable validation (1.9) and ephemeral values (1.10) are.
What happens if I pass an object with extra attributes to a variable typed as object?
Terraform accepts it and silently discards the extra attributes during conversion. No error is raised, which means a misspelled attribute name can go unnoticed. Catch it with a validation rule, by making the attribute required, or by validating the key set with a precondition.
Conclusion
Terraform’s type system is small enough to hold in your head and precise enough that every exam question about it has one defensible answer. Three primitive types, three collection kinds and two structural kinds; literals that are tuples and objects until a constraint converts them; any as a placeholder that must resolve to one concrete type; conversion that is generous for primitives, lossy for object-to-map and set, and absent for equality; optional defaults that overwrite explicit nulls while nullable decides whether null is allowed at all; conversion functions that exist to normalise module outputs; and two orthogonal marks, sensitive and ephemeral, that follow a value wherever it goes. Learn those rules, prove each one in terraform console, and Objective 4d stops being the sub-objective you dread and becomes the one you finish fastest.