Use the Console as a Small Language Laboratory
A spreadsheet formula bar tests one expression without recalculating the workbook. terraform console does the same: it evaluates against variables, locals and state, prints a value, and changes nothing. Start it in a module directory:
terraform console
It reads the last snapshot. Variables, locals and state load without a refresh, so attributes show the last apply; use terraform plan for live infrastructure.
Literals have the usual forms:
locals {
environment = "staging"
replicas = 3
enabled = true
empty = null
ports = [8080, 8443]
tags = { team = "payments", tier = "web" }
}
The literal forms are conventional. Quoted text is a string, a bare numeral is a number, and true is a bool; null means absence. Brackets build a tuple and braces build an object.
Operators are conventional, with one gap. The plus sign adds numbers but never joins text; use a template or format instead. Both arms of a conditional should share a type, and Terraform unifies them, so a string branch wins over a number.
Equality is deep and strict. Lists compare element by element, but a number never equals its string form, so convert before comparing. The conditional expression requires compatible arms; Terraform unifies them, and true ? "yes" : 1 yields "yes".
Figure 1 traces evaluation and its error branches; Figure 2 marks the read-only boundary.
%%{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
E["Expression: literal, reference, operator or conditional"] --> R{"Reference?"}
R -->|"yes"| V["Resolve var, local, path or state value"]
R -->|"no"| T["Type-check and convert operands"]
V --> T
T --> F{"Function call?"}
F -->|"yes"| X["Evaluate the built-in function"]
F -->|"no"| C["Evaluate operator or conditional"]
X --> O{"Result known?"}
C --> O
O -->|"yes"| P["Print the value"]
O -->|"no"| U["Print known after apply"]
T -->|"type mismatch"| D1["Error: unsuitable value"]
V -->|"missing name"| D2["Error: reference not found"]
X -->|"bad argument"| D3["Error: function call failed"]
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 E,P primary;
class R,V,T,F,C,X secondary;
class O,U ok;
class D1,D2,D3 danger;
The widget keeps the worksheet together. The HCL panel is the provider-free module; the Bash panel runs it.
The console reads; it never writes
terraform console evaluates against configuration and the last known state, prints the result, and exits. It does not refresh, plan or call a provider, so a stale attribute is the state's last observation, not live infrastructure.
Strings, Heredocs and Template Directives
A quoted string is a template. A single interpolation keeps the referenced type; a longer string turns the value into text.
Two escape pairs survive templating. A doubled dollar or percent sign produces a literal ${ or %{. Backslash escapes work in quoted strings, while heredocs interpolate without interpreting backslashes, which suits scripts, regexes and Windows paths:
locals {
literal = "$${not_a_reference}"
script = <<-EOT
#!/bin/sh
echo "service=${var.service.name}"
echo 'the price is $0.10'
EOT
}
The <<-EOT form strips indentation. The closing marker stays on its own line, and $0.10 is literal because interpolation starts with a dollar sign and brace.
Directives add control flow. A for directive repeats a body, an if selects one, else supplies the alternative, and endif closes it. Put directives at column zero in a template file, and append a tilde to trim the newline after them:
%{ for host in hosts ~}
${host}.internal
%{ endfor ~}
Whitespace is the most common template bug. Without the trim marker the output carries blank lines around each item, and the result is still text, just not the text the receiving parser expects. An if follows the same pattern:
%{ if enable_tls ~}
tls: true
%{ else ~}
tls: false
%{ endif ~}
The template sees only its map. templatefile binds an explicit variables map, so a template that references a module variable fails with an unknown-variable error. The map is the template's interface and can be reviewed; file() is for raw content with no substitution.
Timing constrains the use. It runs during plan and apply, so the file must exist where Terraform runs. It suits cloud-init and module policy documents, not post-plan content or secrets.
String functions cover smaller edits. Reach for them when a template would be overkill; the constraint column is where the surprises live.
| Function | Result | Constraint |
|---|---|---|
format("%s-%03d", name, port) | One composed string | Placeholders must match the argument types |
join(sep, list) | One string from a list | Elements are converted to strings and joined in order |
split(sep, text) | A list of strings | An empty separator splits into characters |
replace(text, old, new) | Text with every occurrence substituted | Literal unless the pattern is wrapped in slashes |
substr(text, offset, length) | A slice of the text | Offset is zero-based; a negative offset counts from the end, and length -1 takes the rest |
trimspace(text) | Text without outer whitespace | It does not touch whitespace inside the string |
indent(n, text) | Text indented by n spaces | Every line except the first, which YAML blocks rely on |
regex(pattern, text) | Captures or a match | Errors when nothing matches |
regexall(pattern, text) | Every match | Returns an empty list instead of an error |
Figure 3 follows a string from source to rendered value, including a null interpolation and an invalid rendered document.
%%{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
S["Quoted string or heredoc"] --> I{"Interpolation expression?"}
I -->|"value is null"| N["Error: invalid interpolation value"]
I -->|"value present"| D{"Template directive?"}
D -->|"for"| F["Repeat the body for each element"]
D -->|"if"| C["Include the body when true"]
D -->|"none"| O["Keep literal text"]
F --> R["Render the template string"]
C --> R
O --> R
R --> T{"Rendered by templatefile?"}
T -->|"yes"| TF["Read the .tftpl file and bind the vars map"]
T -->|"no"| Q["Use the inline string"]
TF --> V["Validate: JSON, YAML or shell"]
Q --> V
V -->|"invalid"| X["Plan or apply error"]
V -->|"valid"| Z["Pass the value to a resource argument"]
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 S,Z primary;
class I,D,T,V secondary;
class F,C,O,R,Q,TF ok;
class N,X danger;
Transform Collections Without Losing Their Shape
Collection types are not interchangeable. A tuple fixes length and type per position; a list has one element type; a set has unique elements and no order; an object has fixed attributes; a map has arbitrary keys and one value type.
Conversion can change the data. A mixed list unified to strings turns a number into text, a set removes duplicates, and a map forces one value type. An object can hold a string next to a number.
Merge is the headline, and it is shallow. Later arguments win, as the example shows; a nested object under the same key is replaced whole rather than merged inside.
locals {
default_tags = { managed_by = "terraform", owner = "platform" }
service_tags = { owner = "payments", tier = "web" }
tags = merge(local.default_tags, local.service_tags)
}
| Function | Result | Constraint |
|---|---|---|
flatten(list) | A list with one level removed | Removes one level per call |
zipmap(keys, values) | A map from two lists | Lists must match in length; duplicate keys are a data bug |
lookup(map, key, default) | The value or the default | The three-argument form keeps the result type stable |
toset(list) | Unique, unordered set | Drops duplicates and order, which gives stable for_each keys |
tolist(tuple) | One list type | Mixed elements unify; a number beside a string becomes text |
tomap(object) | A map with one value type | Fails when the values are not uniform |
type(value) | The inferred type name | Read-only; useful when for_each rejects a value |
A for expression builds a collection. Brackets produce a tuple; braces produce an object. An if clause filters, and the grouping marker collects values that share a key:
locals {
upper_names = [for name in var.service_names : upper(name)]
enabled = { for name, svc in var.services : name => svc if svc.enabled }
by_team = { for name, svc in var.services : svc.team => name... }
}
Expansion feeds a variadic call. The grouping marker turned a keyed loop into a map of lists. The same three-dot marker spreads a list into separate arguments, which is why it belongs only in a variadic call; without it the function receives one list and fails.
Conversions document the contract. Scalar conversions normalize text, numbers and booleans; shape conversions normalize lists, maps and sets. Each one raises a clear error before a provider has to reject the value. type() prints the inferred type, which shows why a for_each rejected a value:
> type([for name in ["a", "b"] : name])
tuple([
string,
string,
])
The console explains the shape. A for expression over a known-length list produced a tuple, not a list. Wrap it in tolist or toset where the downstream argument requires that shape.
Encode JSON and YAML Instead of Concatenating Them
Hand-built JSON is a trap. A value containing a quote, a backslash or a newline turns the string malformed while it remains a string, so the provider rejects it later or accepts the wrong document.
An encoder handles the escaping. jsonencode takes a value and produces JSON: strings escaped, numbers and booleans bare, null encoded, keys sorted. The widget pairs the policy with the console call that checks it.
The output is deterministic but not byte-identical to hand-written JSON. Terraform escapes HTML characters as Unicode sequences, so the document is valid while its bytes differ. Tests should compare decoded values, not raw text.
The table separates encoders from decoders. A decoder proves syntax, not schema; a decoded object can still lack a required key.
| Function | Result | Constraint |
|---|---|---|
jsonencode(value) | Minified JSON | Escapes HTML characters; bytes differ from hand-written JSON |
jsondecode(text) | The decoded value | Plan-time error on malformed input; no schema validation |
yamlencode(value) | YAML with sorted keys | Quotes strings such as on, yes and no |
yamldecode(text) | The decoded value | Plan-time error on malformed input; no schema validation |
base64encode(text) | Base64 text | Encoding, not encryption; it expands the payload |
urlencode(text) | Percent-encoded text | Suits query components, not whole URLs |
A template is not an encoder. It renders text and leaves the content type to the caller. Use it for cloud-init, where most of the document is literal, and build structured data as an object that an encoder can handle. Do not ask a template to manage commas and braces.
#cloud-config
hostname: ${hostname}
packages:
%{ for pkg in packages ~}
- ${pkg}
%{ endfor ~}
Encode, don't concatenate
A JSON document assembled by string concatenation breaks on the first quote, backslash or newline, and the provider only finds out later. Build the value as an object and let jsonencode or yamlencode own the escaping, ordering and types.
Content type has operational consequences. A file resource such as local_file hashes the exact bytes, so a whitespace edit rewrites it; some providers normalize a policy while others hash user data or expose a base64 variant. An encoder makes the bytes deterministic, but encoding is not encryption: a secret encoded as JSON is still a secret recorded in state.
CIDRs, Files, Time and Hashes Have Different Constraints
Each family fails differently. The table groups the functions by the constraint that surprises most.
| Family | Functions to reach for | Constraint that bites |
|---|---|---|
| Numeric | abs, ceil, floor, max, min, pow, sum | Division yields a fraction; no integer division, so use floor |
| String | format, join, split, replace, regex, regexall, substr, indent | regex errors on no match; regexall returns empty |
| Collection | concat, contains, distinct, flatten, keys, length, lookup, merge, sort, zipmap | flatten is one level; merge is shallow; sets drop duplicates |
| Encoding | base64encode, jsonencode, jsondecode, urlencode, yamlencode, yamldecode, csvdecode | Not encryption; JSON escapes HTML characters; decode errors are plan-time |
| Filesystem | file, fileexists, fileset, filebase64, templatefile, pathexpand | Reads run where Terraform runs; a missing file fails the plan |
| Date and time | formatdate, timeadd, plantimestamp, timestamp | timestamp() changes every evaluation and causes perpetual diffs |
| Hash and crypto | bcrypt, filemd5, filesha256, md5, sha256, base64sha256, uuid, uuidv5 | Hashes are not encryption; MD5/SHA-1 are not for security; uuid() is random |
| Type | can, tobool, tolist, tomap, tonumber, toset, tostring, try, type | Conversion can fail or unify mixed values; try swallows the error |
| IP and CIDR | cidrhost, cidrnetmask, cidrsubnet, cidrsubnets | New prefix cannot exceed the address size; separate calls do not check overlap |
Division and file location are the two surprises. 10 / 4 is 2.5, so a count needs a floor or ceiling. Filesystem functions read where Terraform runs, so use the module path for module files and the root path for root files; a file missing from the module package fails in CI.
Time and randomness break deterministic plans. A timestamp changes on every evaluation and proposes a change forever; the plan-time variant agrees within one plan. uuidv5(namespace, name) is deterministic, while uuid() differs per call. MD5 and SHA-1 should not protect anything new.
The function extends the prefix. cidrsubnet(prefix, newbits, netnum) selects the netnum-th subnet. Eight new bits on a /16 produce /24s:
locals {
vpc_cidr = "10.0.0.0/16"
subnets = {
"us-east-1a" = cidrsubnet(local.vpc_cidr, 8, 0)
"us-east-1b" = cidrsubnet(local.vpc_cidr, 8, 1)
"us-east-1c" = cidrsubnet(local.vpc_cidr, 8, 2)
}
}
The split is regular. The three calls take the first three blocks of the /16, and cidrhost("10.0.2.0/24", 5) returns 10.0.2.5. Several-subnet allocation in one call guarantees no overlap; separate calls do not, so two modules can both claim the same block.
The impossible prefix fails early. cidrsubnet("10.0.0.0/16", 20, 1) asks for a /36, impossible in IPv4. Terraform fails with "insufficient address space" before a provider call. Figure 4 shows the valid split beside that failure.
Handle Optional Data Without Masking Real Errors
Optional data is where expressions become policy. An owner may be omitted, null or an empty string, and those are different states: null is absence, not zero.
try returns the first argument that succeeds. It catches dynamic errors such as a missing attribute or a failed call, not syntax, provider or apply-time failures, and it does not treat null as failure. A present-but-null attribute passes straight through to the result. coalesce returns the first argument that is neither null nor empty:
locals {
owner = coalesce(var.service.owner, "platform")
}
Zero is a value. coalesce does not skip the number zero, because zero is a valid value. can evaluates an expression and returns a boolean, which makes it a good fit for validation:
validation {
condition = can(regex("^[a-z][a-z0-9-]{2,24}$", var.service_name))
error_message = "Use 3 to 25 lowercase letters, digits or hyphens."
}
Keep can narrow. Wrapping the whole object also returns false for a typo in an attribute name, so the message blames the wrong thing.
A fallback can hide the error that explains the problem
Both try and coalesce turn an error into a value. At a boundary where absence is expected, that is honest; used to keep a plan moving, it produces a working plan with the wrong data. A misspelled attribute plus a default is a valid plan and a silent defect.
Prefer a type constraint or an explicit default. Make the absence visible in the type rather than discovering it at use:
variable "service" {
type = object({
name = string
port = optional(number, 8080)
enabled = optional(bool, true)
owner = optional(string)
})
}
A default and a rejection are different tools. optional(number, 8080) fills an omitted attribute; the form without a default leaves null. Set nullable = false when null itself should be rejected.
Conversions belong at the same boundary. A scalar conversion such as tonumber normalizes text, numbers and booleans; shape conversions normalize lists, maps and sets. Each one raises a clear error before a provider has to reject the value. A value known only after apply cannot become a plan-time boolean.
Let the type carry the policy
Describe what may be omitted in the type, let a default fill the gap, and keep the validation check narrow. Use coalesce for null or empty text, and keep try close to an absence you can name; if it exists only to keep the plan moving, delete it and fix the data.
Build a network and tagging data model
Execution status: design-only. It needs no provider or cloud account. Use Terraform CLI 1.17.1, the version this series pins, verified 5 November 2026. The expected values are illustrative checks, not captured production output.
Prerequisites. A scratch directory, Terraform CLI 1.17.1 on the shell path, and no credentials. Create main.tf with the variables and locals from the code widget, then run terraform init -input=false once.
Worksheet checks. Open terraform console and confirm the identity and formatting cases first:
| Expression | Expected |
|---|---|
2 + 3 * 4 | 14 |
local.name_prefix | staging-checkout |
local.base_tags | three keys |
local.tls_enabled | true |
1 == "1" | false |
tonumber("1") == 1 | true |
- Create
bootstrap.tftplwith the cloud-init loop; render it intolocal.user_datawithtemplatefile("${path.module}/bootstrap.tftpl", { hostname = local.name_prefix, packages = ["nginx", "jq"] })and confirm one-line per package. - Run
yamldecode(local.user_data); it should returnhostnameand a two-element list. If it fails, inspect whitespace first. - Round-trip an IAM-style policy through
jsonencodeandjsondecode; note the sorted keys. - Allocate three
/24subnets from10.0.0.0/16withcidrsubnet. Confirm10.0.0.0/24,10.0.1.0/24and10.0.2.0/24, then read the "insufficient address space" error fromcidrsubnet("10.0.0.0/16", 20, 1). - With
owneromitted, comparetry(var.service.owner, "platform")andcoalesce(var.service.owner, "platform"). Setowner = nulland repeat:tryreturns null, whilecoalescereturns"platform". - Introduce a typo such as
try(var.service.prt, 8080). It returns 8080 with no error. Remove thetry, evaluate again, and read the unsupported-attribute error.
Expected observation. A stable worksheet, a cloud-init document that decodes cleanly, a JSON round trip with sorted keys, and three non-overlapping /24 prefixes. The failures show that a fallback catches a missing attribute but not a present null.
Failure check. An unknown-variable error from the template means it references a module variable instead of its map. A decode failure usually means blank lines or wrong indentation around the loop. A subnet failure means the requested prefix exceeds the address size for the IP version.
Cost and cleanup. Zero cloud cost. Delete the scratch directory, including .terraform/ and local state. Do not commit a rendered bootstrap file with environment-specific values.
Next in the Series
In Count, For Each and Dynamic Blocks Without Address Surprises, we'll explore Choose stable resource identities and distinguish resource repetition from value transformations.