Andrew Mercer
on this page

An expression computes a value. Literals, references, operators, function calls, conditionals, for expressions and templates are all expressions, and they nest freely.

Two kinds get their own pages: conditionals (the ternary operator) and for expressions.

References

Reference Refers to
var.<name> Input variable
local.<name> Local value
<type>.<name> Managed resource, e.g. azurerm_subnet.app
<type>.<name>[<key>] One instance of a resource using count/for_each
data.<type>.<name> Data source
ephemeral.<type>.<name> Ephemeral resource
module.<name>.<output> Child module output
path.module Filesystem path of the current module
path.root Path of the root module
path.cwd Working directory. Avoid; it changes depending on where Terraform runs
terraform.workspace Current CLI workspace name
terraform.applying true during apply. Ephemeral-only (Terraform 1.10+)
count.index Index inside a count resource
each.key, each.value Current element inside a for_each resource
self The resource itself, only inside provisioners, connection and postconditions

Every reference to another object creates a graph edge. That's how implicit dependencies work (dependencies).

Indexing and attribute access

var.subnets["aks"].address_prefix   # map key, then attribute
var.zones[0]                         # list index
azurerm_subnet.this["aks"].id        # for_each instance
azurerm_public_ip.lb[count.index].ip_address

Legacy var.list.0 dot-index syntax still parses but use brackets.

Operators

In precedence order, highest first:

Operators Meaning
!, unary - Logical NOT, negation
*, /, % Multiply, divide, modulo
+, - Add, subtract (numbers only. Strings use templates or join)
>, >=, <, <= Numeric comparison
==, != Equality (type-sensitive: 5 == "5" is false)
&& Logical AND
\|\| Logical OR
? : Conditional

Short-circuiting depends on your version. Terraform 1.12+ short-circuits && and ||: if the left side decides the result, the right side isn't evaluated. Older Terraform (and OpenTofu, unless its docs say otherwise for your version) evaluates both sides, so this errors when var.config is null:

# Errors on Terraform < 1.12 (var.config.enabled is evaluated even when null).
# Works on 1.12+.
condition = var.config != null && var.config.enabled

# ✅ Portable: a conditional only evaluates the chosen branch
condition = var.config != null ? var.config.enabled : false

# ✅ Portable: try()
condition = try(var.config.enabled, false)

In shared modules that might run on older Terraform or on OpenTofu, write the portable form.

Strings

Quoted strings and escapes

name    = "rg-${var.app}-${var.env}"
path    = "C:\\Temp\\file.txt"   # \\ \" \n \r \t \uNNNN \UNNNNNNNN
literal = "Costs $${var.x}"       # $${ escapes interpolation → "Costs ${var.x}"
percent = "100%%{x}"              # %%{ escapes directives

Heredocs

# Standard heredoc: content keeps its indentation
custom_data = <<EOT
#!/bin/bash
echo "hello"
EOT

# Indented heredoc (<<-): strips the common leading whitespace,
# so you can indent it with the surrounding code
policy = <<-EOT
  {
    "Version": "2012-10-17"
  }
EOT

Don't build JSON in heredocs. Use jsonencode() so quoting and escaping are always right:

policy = jsonencode({
  Version   = "2012-10-17"
  Statement = [{ Effect = "Allow", Action = ["s3:GetObject"], Resource = "${aws_s3_bucket.b.arn}/*" }]
})

Interpolation

${ ... } inside a string evaluates any expression and converts the result to a string. A string that is only an interpolation, like "${var.x}", is a legacy 0.11 pattern. Write var.x. terraform fmt won't fix it for you but tflint's terraform_deprecated_interpolation rule will flag it.

Template directives

Directives give strings if and for:

locals {
  hosts = ["web1", "web2", "web3"]

  hosts_file = <<-EOT
    %{ for i, h in local.hosts ~}
    10.0.0.${i + 10} ${h}
    %{ endfor ~}
  EOT

  greeting = "Hello, %{ if var.name != "" }${var.name}%{ else }stranger%{ endif }!"
}

The ~ strip marker removes whitespace (including the newline) on that side of the directive. Without it, every %{ for } line leaves a blank line in the output.

For anything more than a few lines, move the template into a file and use templatefile():

custom_data = base64encode(templatefile("${path.module}/templates/cloud-init.yaml.tftpl", {
  hostname = var.hostname
  ssh_keys = var.ssh_keys
}))

.tftpl is the conventional extension. templatestring() (Terraform 1.9+) renders a template held in a string value, which is useful when the template comes from a data source.

Splat expressions

[*] is shorthand for a simple for expression over a list:

azurerm_network_interface.nic[*].private_ip_address
# same as
[for nic in azurerm_network_interface.nic : nic.private_ip_address]

Rules:

  • Splat works on lists, sets and tuples, so count resources. For for_each resources (maps), use values(azurerm_x.this)[*].id or a for expression.
  • Applied to a single non-list value, [*] wraps it in a one-element list, and turns null into []. That's a handy trick for optional nested blocks: for_each = var.backup[*] gives zero or one iterations (dynamic blocks).
  • The legacy .* attribute-only splat still exists; prefer [*].

Function calls and argument expansion

max(5, 12, 9)              # 12
max(var.numbers...)        # expand a list into separate arguments
merge(local.tag_maps...)   # merge a list of maps

... after the final argument expands a list or tuple into positional arguments. It's the idiomatic way to merge() a computed list of maps.

All built-in functions are documented on the functions page. Provider-defined functions are called with a namespace: provider::azurerm::parse_resource_id(id).

Expressions that must be known at plan time

These arguments shape the graph, so their values must be known during planning:

  • count and for_each, including the keys of a for_each map (values may be unknown)
  • Module source and version (Terraform 1.15+ lets them use variables and locals, but still only values known before init. OpenTofu has supported this since 1.8)
  • provider meta-argument references
  • Backend configuration (literals only in Terraform. OpenTofu 1.8+ allows variables and locals)
  • moved, import.to, removed.from addresses

When you hit "cannot be determined until apply", restructure so the key comes from input (a variable or a static map) rather than from a resource attribute.