Back to Terraform

Expressions and Functions: Turn Inputs into Infrastructure Data

November 5, 2026 Wasil Zafar 21 min read

Use Terraform console to reason about strings, collections, encodings, CIDRs and conditional values

Table of Contents

  1. Use the Console as a Small Language Laboratory
  2. Strings, Heredocs and Template Directives
  3. Transform Collections Without Losing Their Shape
  4. Encode JSON and YAML Instead of Concatenating Them
  5. CIDRs, Files, Time and Hashes Have Different Constraints
  6. Handle Optional Data Without Masking Real Errors

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.

Use the Console as a Small Language Laboratory
%%{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 console reads configuration and state but writes nothing Variables, locals and state flow into the console evaluator, which prints a value. No arrow reaches the provider API. A read-only bench for the configuration language Read-only inputs var.* and local.* defaults and tfvars resource attributes from the current state path.module, path.root and path.cwd read terraform console evaluate convert print print value on screen no state write Provider API no plan, apply, refresh or remote write blocked The boundary is the point: console answers questions without touching infrastructure.

The widget keeps the worksheet together. The HCL panel is the provider-free module; the Bash panel runs it.

variable "environment" {
  type    = string
  default = "staging"
}

variable "service" {
  type = object({
    name  = string
    ports = list(number)
    tags  = map(string)
  })
  default = {
    name  = "checkout"
    ports = [8080, 8443]
    tags  = { team = "payments", tier = "web" }
  }
}

locals {
  is_production = var.environment == "prod"
  primary_port  = var.service.ports[0]
  instance_type = local.is_production ? "m6i.large" : "t3.small"
  name_prefix   = "${var.environment}-${var.service.name}"
  base_tags     = merge({ managed_by = "terraform" }, var.service.tags)
  port_list     = join(",", [for p in var.service.ports : tostring(p)])
  tls_enabled   = contains(var.service.ports, 443) || contains(var.service.ports, 8443)
}
terraform init -input=false

c() { echo "$1" | terraform console; }

c '2 + 3 * 4'                  # => 14
c '(2 + 3) * 4'                # => 20
c 'local.primary_port'         # => 8080
c 'local.is_production'        # => false
c 'local.instance_type'        # => "t3.small"
c 'local.name_prefix'          # => "staging-checkout"
c 'local.base_tags'            # => three keys
c 'local.port_list'            # => "8080,8443"
c 'local.tls_enabled'          # => true
c '"web" == "web"'             # => true
c '1 == "1"'                   # => false
c 'local.is_production ? "blue" : "green"'  # => "green"

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.

FunctionResultConstraint
format("%s-%03d", name, port)One composed stringPlaceholders must match the argument types
join(sep, list)One string from a listElements are converted to strings and joined in order
split(sep, text)A list of stringsAn empty separator splits into characters
replace(text, old, new)Text with every occurrence substitutedLiteral unless the pattern is wrapped in slashes
substr(text, offset, length)A slice of the textOffset is zero-based; a negative offset counts from the end, and length -1 takes the rest
trimspace(text)Text without outer whitespaceIt does not touch whitespace inside the string
indent(n, text)Text indented by n spacesEvery line except the first, which YAML blocks rely on
regex(pattern, text)Captures or a matchErrors when nothing matches
regexall(pattern, text)Every matchReturns 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.

Strings, Heredocs and Template Directives
%%{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)
}
FunctionResultConstraint
flatten(list)A list with one level removedRemoves one level per call
zipmap(keys, values)A map from two listsLists must match in length; duplicate keys are a data bug
lookup(map, key, default)The value or the defaultThe three-argument form keeps the result type stable
toset(list)Unique, unordered setDrops duplicates and order, which gives stable for_each keys
tolist(tuple)One list typeMixed elements unify; a number beside a string becomes text
tomap(object)A map with one value typeFails when the values are not uniform
type(value)The inferred type nameRead-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.

locals {
  bucket_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Effect   = "Allow"
      Action   = "s3:GetObject"
      Resource = "${var.bucket_arn}/*"
    }]
  })
}
terraform console <<'EOF'
local.bucket_policy
EOF

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.

FunctionResultConstraint
jsonencode(value)Minified JSONEscapes HTML characters; bytes differ from hand-written JSON
jsondecode(text)The decoded valuePlan-time error on malformed input; no schema validation
yamlencode(value)YAML with sorted keysQuotes strings such as on, yes and no
yamldecode(text)The decoded valuePlan-time error on malformed input; no schema validation
base64encode(text)Base64 textEncoding, not encryption; it expands the payload
urlencode(text)Percent-encoded textSuits 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.

FamilyFunctions to reach forConstraint that bites
Numericabs, ceil, floor, max, min, pow, sumDivision yields a fraction; no integer division, so use floor
Stringformat, join, split, replace, regex, regexall, substr, indentregex errors on no match; regexall returns empty
Collectionconcat, contains, distinct, flatten, keys, length, lookup, merge, sort, zipmapflatten is one level; merge is shallow; sets drop duplicates
Encodingbase64encode, jsonencode, jsondecode, urlencode, yamlencode, yamldecode, csvdecodeNot encryption; JSON escapes HTML characters; decode errors are plan-time
Filesystemfile, fileexists, fileset, filebase64, templatefile, pathexpandReads run where Terraform runs; a missing file fails the plan
Date and timeformatdate, timeadd, plantimestamp, timestamptimestamp() changes every evaluation and causes perpetual diffs
Hash and cryptobcrypt, filemd5, filesha256, md5, sha256, base64sha256, uuid, uuidv5Hashes are not encryption; MD5/SHA-1 are not for security; uuid() is random
Typecan, tobool, tolist, tomap, tonumber, toset, tostring, try, typeConversion can fail or unify mixed values; try swallows the error
IP and CIDRcidrhost, cidrnetmask, cidrsubnet, cidrsubnetsNew 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.

A valid CIDR split and an impossible one A /16 is split with eight new bits into /24 subnets at 10.0.0.0, 10.0.1.0 and 10.0.2.0. Twenty new bits would require a /36, so cidrsubnet fails before any provider call. One prefix, two futures VPC prefix: 10.0.0.0/16 65,536 addresses cidrsubnet(..., 8, n) 10.0.0.0/24 netnum 0, 256 addresses 10.0.1.0/24 netnum 1, 256 addresses 10.0.2.0/24 netnum 2, 256 addresses valid split invalid split cidrsubnet(..., 20, 1) asks for a /36 prefix 16 + 20 = 36 > 32 Error: insufficient space The failing call is a plan-time error. No provider is called and no infrastructure is touched.

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.

Lab

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:

ExpressionExpected
2 + 3 * 414
local.name_prefixstaging-checkout
local.base_tagsthree keys
local.tls_enabledtrue
1 == "1"false
tonumber("1") == 1true
  1. Create bootstrap.tftpl with the cloud-init loop; render it into local.user_data with templatefile("${path.module}/bootstrap.tftpl", { hostname = local.name_prefix, packages = ["nginx", "jq"] }) and confirm one - line per package.
  2. Run yamldecode(local.user_data); it should return hostname and a two-element list. If it fails, inspect whitespace first.
  3. Round-trip an IAM-style policy through jsonencode and jsondecode; note the sorted keys.
  4. Allocate three /24 subnets from 10.0.0.0/16 with cidrsubnet. Confirm 10.0.0.0/24, 10.0.1.0/24 and 10.0.2.0/24, then read the "insufficient address space" error from cidrsubnet("10.0.0.0/16", 20, 1).
  5. With owner omitted, compare try(var.service.owner, "platform") and coalesce(var.service.owner, "platform"). Set owner = null and repeat: try returns null, while coalesce returns "platform".
  6. Introduce a typo such as try(var.service.prt, 8080). It returns 8080 with no error. Remove the try, 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.