Andrew Mercer
on this page

Terraform has no user-defined functions. What you get is a fixed library of built-ins, plus provider-defined functions (Terraform 1.8+, OpenTofu 1.7+) that providers ship. This page lists every built-in as of Terraform 1.16, grouped the way the official docs group them, with an example for each.

Conventions on this page:

  • → shows the result, as terraform console would print it.
  • Bold functions are the ones you'll use weekly.
  • Try any of them in terraform console (or tofu console) before using them in configuration.

Call syntax recap (expressions):

max(5, 12, 9)                 # positional arguments
max(var.numbers...)           # expand a list into arguments
provider::azurerm::normalise_resource_id(var.id)   # provider-defined function

Numeric functions

Function Does Example → result
abs(n) Absolute value abs(-12.4) → 12.4
ceil(n) Round up to the nearest whole number ceil(4.1) → 5
floor(n) Round down floor(4.9) → 4
log(n, base) Logarithm log(16, 2) → 4
max(n...) Largest number max(5, 12, 9) → 12
min(n...) Smallest number min(5, 12, 9) → 5
parseint(s, base) Parse a string in base 2–62 parseint("FF", 16) → 255
pow(base, exp) Exponent pow(2, 10) → 1024
signum(n) -1, 0 or 1 signum(-3) → -1

Notes:

  • There's no round(). Use floor(n + 0.5).
  • Integer division: floor(7 / 2) → 3. The / operator always returns a fractional result.
  • max()/min() on an empty list error. Guard with length(l) > 0 ? max(l...) : 0.

String functions

Function Does Example → result
chomp(s) Remove trailing newlines chomp("hi\n") → "hi"
endswith(s, suffix) Suffix test endswith("app.json", ".json") → true
format(spec, args...) printf-style formatting format("vm-%s-%02d", "web", 3) → "vm-web-03"
formatlist(spec, lists...) format over lists element-wise formatlist("%s.example.com", ["a","b"]) → ["a.example.com","b.example.com"]
indent(n, s) Indent every line except the first indent(2, "a\nb") → "a\n b"
join(sep, list) Join a list into a string join(",", ["a","b"]) → "a,b"
lower(s) Lowercase lower("WEB") → "web"
regex(pattern, s) First match (errors if none) regex("^([a-z]+)-(\\d+)$", "web-01") → ["web", "01"]
regexall(pattern, s) All matches (empty list if none) length(regexall("prod", var.name)) > 0
replace(s, find, repl) Replace substring, or regex if find is /.../ replace("a-b-c", "-", "_") → "a_b_c"
split(sep, s) String → list split(",", "a,b") → ["a","b"]
startswith(s, prefix) Prefix test startswith("rg-app", "rg-") → true
strcontains(s, sub) Substring test (1.5+) strcontains("vnet-prod-cc", "prod") → true
strrev(s) Reverse strrev("abc") → "cba"
substr(s, offset, len) Substring; len = -1 means "to the end" substr("canadacentral", 0, 6) → "canada"
templatestring(ref, vars) Render a template held in a string value (1.9+) templatestring(local.tpl, { name = "x" })
title(s) Capitalise each word title("hello world") → "Hello World"
trim(s, chars) Remove any of chars from both ends trim("--a--", "-") → "a"
trimprefix(s, p) Remove a prefix once trimprefix("rg-app", "rg-") → "app"
trimsuffix(s, p) Remove a suffix once trimsuffix("app.tf", ".tf") → "app"
trimspace(s) Remove surrounding whitespace trimspace(" a \n") → "a"
upper(s) Uppercase upper("web") → "WEB"

Patterns:

locals {
  # Azure storage account names: 3-24 chars, lowercase alphanumerics only
  storage_name = substr(lower(replace("st${var.workload}${var.env}", "/[^a-z0-9]/", "")), 0, 24)

  # Parse a resource ID without a provider function
  rg_name = regex("/resourceGroups/([^/]+)", var.resource_id)[0]

  # Named capture groups return an object
  parts = regex("^(?P<app>[a-z]+)-(?P<env>dev|test|prod)$", "billing-prod")
  # → { app = "billing", env = "prod" }
}

Gotchas:

  • regex() errors when there's no match. In validations use can(regex(...)); elsewhere use regexall() and check length.
  • Regex syntax is RE2 (Go). No lookarounds or backreferences.
  • In HCL strings, backslashes must be doubled: "\\d+".
  • replace() only uses regex when the search string is wrapped in slashes: "/[^a-z]/".
  • substr() counts Unicode characters, not bytes. A length past the end is clamped, so substr(s, 0, 24) is the safe way to truncate.

Collection functions

Function Does Example → result
alltrue(list) All elements true (empty → true) alltrue([for s in var.subnets : s.private])
anytrue(list) Any element true (empty → false) anytrue([true, false]) → true
chunklist(list, n) Split into chunks of n chunklist([1,2,3], 2) → [[1,2],[3]]
coalesce(vals...) First non-null, non-empty-string value coalesce(var.loc, "canadacentral")
coalescelist(lists...) First non-empty list coalescelist(var.dns, ["168.63.129.16"])
compact(list) Drop null and "" from a list of strings compact(["a", "", null]) → ["a"]
concat(lists...) Join lists concat(["a"], ["b","c"]) → ["a","b","c"]
contains(list, v) Membership test (1.16: can test for null) contains(["dev","prod"], var.env)
distinct(list) Remove duplicates, keep first occurrence order distinct(["a","b","a"]) → ["a","b"]
element(list, i) Element at index, wrapping around element(["a","b"], 3) → "b"
flatten(list) Flatten nested lists flatten([["a"],["b",["c"]]]) → ["a","b","c"]
index(list, v) Index of first match (errors if missing) index(["a","b"], "b") → 1
keys(map) Sorted list of keys keys({b=1,a=2}) → ["a","b"]
length(v) Length of list, map or string length("abc") → 3
lookup(map, key, default) Map lookup with default lookup(local.skus, var.env, "B1")
matchkeys(vals, keys, search) Filter vals where the matching keys element is in search matchkeys(["i1","i2"], ["a","b"], ["b"]) → ["i2"]
merge(maps...) Merge maps/objects; later wins (shallow) merge(var.tags, { env = "dev" })
one(list) The only element, null if empty, error if >1 one(azurerm_x.this[*].id)
range(start?, limit, step?) Number sequence range(3) → [0,1,2]; range(1, 10, 3) → [1,4,7]
reverse(list) Reverse order reverse([1,2,3]) → [3,2,1]
setintersection(sets...) Elements in all sets setintersection(["a","b"], ["b","c"]) → ["b"]
setproduct(sets...) Cartesian product setproduct(["dev","prod"], ["cc","ce"]) → 4 pairs
setsubtract(a, b) Elements in a but not b setsubtract(["a","b"], ["b"]) → ["a"]
setunion(sets...) Elements in any set setunion(["a"], ["b"]) → ["a","b"]
slice(list, start, end) Sub-list, end exclusive slice(["a","b","c"], 0, 2) → ["a","b"]
sort(list) Lexical sort of strings sort(["b","a","10","9"]) → ["10","9","a","b"]
sum(list) Sum of numbers sum([1,2,3]) → 6
transpose(map) Swap keys and values in a map of lists transpose({a=["x"], b=["x","y"]}) → {x=["a","b"], y=["b"]}
values(map) Values in key order values({b=1,a=2}) → [2,1]
zipmap(keys, values) Build a map from two lists zipmap(["a","b"], [1,2]) → {a=1,b=2}
list(...) Deprecated since 0.12. Use tolist() or [...]
map(...) Deprecated since 0.12. Use tomap() or {...}

Gotchas:

  • merge() is shallow. Nested maps are replaced, not merged:

hcl merge({ tags = { a = 1 } }, { tags = { b = 2 } }) # → { tags = { b = 2 } }

Merge nested maps explicitly: merge(var.defaults.tags, var.overrides.tags).

  • sort() is lexical, so numbers-as-strings sort as "10" < "9". There's no numeric sort; zero-pad, or compute with min/max.
  • element() wraps around silently. list[i] errors on an out-of-range index, which is usually what you want.
  • index() errors when the value is missing. Guard with contains() first.
  • lookup() without a default errors on a missing key; with structural types, plain indexing map[key] is clearer and gives a better error.
  • keys() and values() are sorted by key, so they line up with each other.
  • distinct() and setunion() differ on ordering: distinct() preserves first-seen order, sets don't promise order.

Encoding functions

Function Does Example → result
base64decode(s) Base64 → UTF-8 string base64decode("aGk=") → "hi"
base64encode(s) String → Base64 base64encode("hi") → "aGk="
base64gzip(s) Gzip then Base64 (cloud-init custom_data size limits) base64gzip(local.cloud_init)
csvdecode(s) CSV with header row → list of maps csvdecode(file("${path.module}/users.csv"))
jsondecode(s) JSON → value jsondecode(file("config.json")).regions
jsonencode(v) Value → JSON jsonencode({ a = 1 }) → "{\"a\":1}"
textdecodebase64(s, enc) Base64 → string in a given encoding textdecodebase64(var.b64, "UTF-16LE")
textencodebase64(s, enc) String → Base64 in a given encoding textencodebase64("Hello", "UTF-16LE") (PowerShell -EncodedCommand)
urlencode(s) URL query encoding urlencode("a b") → "a+b"
yamldecode(s) YAML → value yamldecode(file("envs/${var.env}.yaml"))
yamlencode(v) Value → YAML Kubernetes manifests, Helm values

Patterns:

locals {
  # Environments-as-data: one YAML file per environment
  env = yamldecode(file("${path.module}/envs/${var.environment}.yaml"))

  # Bulk-create users from a CSV maintained by someone else
  users = { for u in csvdecode(file("${path.module}/users.csv")) : u.upn => u }
}

Always use jsonencode() for JSON policy documents and ARM/Bicep-style payloads. Hand-written JSON in heredocs produces perpetual diffs when whitespace or key order changes.

Filesystem functions

Function Does Example
abspath(p) Absolute path abspath(path.root)
basename(p) Last path element basename("a/b/c.txt") → "c.txt"
dirname(p) All but the last element dirname("a/b/c.txt") → "a/b"
pathexpand(p) Expand ~ pathexpand("~/.ssh/id_ed25519.pub")
file(p) Read a file as UTF-8 text file("${path.module}/scripts/init.sh")
filebase64(p) Read a file as Base64 (binary-safe) filebase64("${path.module}/cert.pfx")
fileexists(p) Does the file exist? fileexists("${path.module}/overrides.yaml")
fileset(dir, pattern) Glob files in a directory fileset("${path.module}/policies", "*.json")
templatefile(p, vars) Render a template file templatefile("${path.module}/tpl/cloud-init.tftpl", { host = var.host })

Rules:

  • Always prefix with path.module. Relative paths resolve against the working directory, which differs between terraform, Terragrunt's cache directory and CI.
  • These functions read files at plan time from the configuration directory. They can't read files a resource creates during apply. For that, use the local_file data source with an explicit dependency.
  • Don't file() secrets into configuration. The contents end up in state and plan files.
# Upload every policy definition in a folder
resource "azurerm_policy_definition" "custom" {
  for_each = fileset("${path.module}/policies", "*.json")

  name         = trimsuffix(each.value, ".json")
  policy_type  = "Custom"
  mode         = "All"
  display_name = trimsuffix(each.value, ".json")
  policy_rule  = jsonencode(jsondecode(file("${path.module}/policies/${each.value}")).policyRule)
}

Date and time functions

Function Does Example
formatdate(spec, ts) Format an RFC 3339 timestamp formatdate("YYYY-MM-DD", timestamp())
plantimestamp() Timestamp fixed at plan time (1.5+) expiry = timeadd(plantimestamp(), "720h")
timeadd(ts, duration) Add a duration ("24h", "-10m") timeadd("2026-01-01T00:00:00Z", "24h")
timecmp(a, b) Compare timestamps: -1, 0, 1 timecmp(var.cert_expiry, plantimestamp()) > 0
timestamp() Current time at apply. Unknown during plan Avoid in resource arguments

timestamp() produces a new value on every run, so any argument using it shows a perpetual diff. Use plantimestamp() when you need "now" in a plan, or the time_static / time_rotating resources from the hashicorp/time provider when you need a timestamp that's stored once and stays stable:

resource "time_rotating" "sp_secret" {
  rotation_days = 90
}

resource "azuread_application_password" "this" {
  application_id = azuread_application.this.id
  end_date       = time_rotating.sp_secret.rotation_rfc3339
  rotate_when_changed = {
    rotation = time_rotating.sp_secret.id
  }
}

Hash and crypto functions

Function Does
base64sha256(s) SHA-256, Base64-encoded (AWS Lambda source_code_hash)
base64sha512(s) SHA-512, Base64-encoded
bcrypt(s, cost?) Bcrypt hash. New salt every run → perpetual diff. Avoid in resources
filebase64sha256(p) base64sha256(file(p)) without loading text (binary-safe)
filebase64sha512(p) Same, SHA-512
filemd5(p) MD5 hex of a file
filesha1(p) SHA-1 hex of a file
filesha256(p) SHA-256 hex of a file
filesha512(p) SHA-512 hex of a file
md5(s) MD5 hex
rsadecrypt(ct, key) Decrypt RSA ciphertext (Windows admin passwords on AWS)
sha1(s) SHA-1 hex
sha256(s) SHA-256 hex
sha512(s) SHA-512 hex
uuid() Random UUID. New every run. Use random_uuid instead
uuidv5(ns, name) Deterministic name-based UUID. Stable, so safe in resources

The main legitimate uses are change triggers and deterministic names:

resource "terraform_data" "bootstrap" {
  triggers_replace = {
    script_hash = filesha256("${path.module}/scripts/bootstrap.sh")
  }
  # ...
}

locals {
  # Short, stable, unique-ish suffix (e.g. for globally unique storage names)
  suffix = substr(sha256("${var.subscription_id}/${var.workload}"), 0, 6)
}

IP network functions

Function Does Example → result
cidrhost(prefix, n) Nth host address in a prefix (negative counts from the end) cidrhost("10.0.1.0/24", 4) → "10.0.1.4"
cidrnetmask(prefix) Dotted netmask (IPv4 only) cidrnetmask("10.0.0.0/22") → "255.255.252.0"
cidrsubnet(prefix, newbits, num) Carve the Nth subnet of size prefix+newbits cidrsubnet("10.10.0.0/16", 8, 4) → "10.10.4.0/24"
cidrsubnets(prefix, newbits...) Carve consecutive, non-overlapping subnets of varying sizes see below
locals {
  vnet_cidr = "10.10.0.0/16"

  # /22 for AKS, /24 for data, /24 for web, /26 for bastion. Consecutive, no gaps
  subnet_cidrs = cidrsubnets(local.vnet_cidr, 6, 8, 8, 10)
  # → ["10.10.0.0/22", "10.10.4.0/24", "10.10.5.0/24", "10.10.6.0/26"]

  subnets = zipmap(["aks", "data", "web", "AzureBastionSubnet"], local.subnet_cidrs)
}

Changing the order or sizes in cidrsubnets() renumbers every later subnet, which destroys and recreates them. Append new subnets at the end, or allocate with cidrsubnet() and explicit indexes so existing ranges never move.

Azure reserves the first four addresses and the last address in each subnet, so the first usable host is cidrhost(prefix, 4).

Type conversion functions

Function Does
can(expr) true if the expression evaluates without error
convert(v, type) Convert to an exact type constraint inline (Terraform 1.15+)
ephemeralasnull(v) Replace ephemeral values with null so the rest can be stored (1.10+)
issensitive(v) Is the value marked sensitive? (1.8+)
nonsensitive(v) Remove the sensitive mark. Only on values that are actually safe to show
sensitive(v) Add the sensitive mark
tobool(v) Convert to bool
tolist(v) Convert to list
tomap(v) Convert to map
tonumber(v) Convert to number
toset(v) Convert to set (dedupes, loses order)
tostring(v) Convert to string
try(exprs...) First expression that evaluates without error
type(v) Show a value's type. terraform console only
variable "subnet_cidr" {
  type = string
  validation {
    condition     = can(cidrnetmask(var.subnet_cidr))
    error_message = "subnet_cidr must be a valid IPv4 CIDR, e.g. 10.0.1.0/24."
  }
}

locals {
  # Tolerate optional keys in decoded YAML
  replicas = try(local.env.app.replicas, 1)
}

try() and can() only catch dynamic errors (missing attributes, failed conversions, regex non-matches). Syntax errors and references to undeclared variables still fail the plan.

Terraform-specific and provider-defined functions

The built-in terraform provider's functions

These ship with Terraform itself and are called with the provider::terraform:: prefix. They don't need a required_providers entry.

Function Does
provider::terraform::encode_tfvars(obj) Object → .tfvars file content
provider::terraform::decode_tfvars(s) .tfvars content → object
provider::terraform::encode_expr(v) Value → HCL expression source text
resource "local_file" "child_tfvars" {
  filename = "${path.module}/generated/child.auto.tfvars"
  content  = provider::terraform::encode_tfvars({
    environment = var.environment
    tags        = local.tags
  })
}

Handy when a Terraform stack generates configuration for another tool, or for your own CLI tooling to read.

Provider-defined functions

Providers can export pure functions (Terraform 1.8+, OpenTofu 1.7+). Declare the provider in required_providers and call it with provider::<local_name>::<function>:

terraform {
  required_providers {
    azurerm = { source = "hashicorp/azurerm", version = "~> 4.0" }
  }
}

locals {
  parsed = provider::azurerm::parse_resource_id(var.key_vault_id)
  kv_rg  = local.parsed.resource_group_name
}

Commonly useful ones (check each provider's registry page; the list changes):

  • azurerm: parse_resource_id, normalise_resource_id
  • aws: arn_parse, arn_build, trim_iam_role_path
  • google: region_from_id, name_from_id, project_from_id
  • kubernetes: manifest_decode, manifest_encode

OpenTofu users can also pull in community function providers (for example, one that runs Lua) to get something close to user-defined functions. That makes the module OpenTofu-dependent; check maintenance status before adopting one.

OpenTofu-only built-ins

OpenTofu has a few built-ins Terraform doesn't (check the OpenTofu page for current differences):

Function Does
base64gunzip(s) Inverse of base64gzip
cidrcontains(prefix, ip_or_prefix) Is an address or prefix within a CIDR?
urldecode(s) Inverse of urlencode

Using these makes a module OpenTofu-only. Don't use them in modules shared with Terraform users.

Functions that run at special times

Most functions are pure: same inputs, same output, any time. A few aren't:

Function Behaviour
file, templatefile, fileset, fileexists, file*sha* Evaluated during validation/plan from the configuration directory
timestamp, uuid, bcrypt Different every run. Unknown during plan for timestamp; perpetual diffs in resource arguments
plantimestamp Fixed for the whole plan, same value at apply