Terraform 18: Built-in functions & expressions
easy⏱ 5 mincourseterraform
Expressions compute values
Anywhere HCL expects a value you can write an expression: a reference, an operator, or a function call. Functions are pure — same inputs, same output, no side effects. You compose them to derive names and settings from a few inputs so nothing is repeated by hand.
locals {
org = "myorg"
service = "orders"
environment = "dev"
# format("%s-%s-%s", ...) builds a printf-style string
name_prefix = format("%s-%s-%s", local.org, local.service, local.environment)
# join(sep, list) glues a list with a separator -> "orders,billing"
csv_scopes = join(",", ["orders", "billing"])
}
resource "azurerm_resource_group" "main" {
name = format("%s-rg", local.name_prefix) # myorg-orders-dev-rg
location = "westus2"
}
lookup, merge & coalesce
lookup(map, key, default) reads a map with a fallback so a missing key never crashes the plan. merge(a, b, ...) shallow-combines maps, with later keys winning — the idiom for layering base tags with per-resource tags. coalesce(a, b, ...) returns the first non-null / non-empty argument — perfect for "use the override, else the default".
locals {
base_tags = {
managed_by = "terraform"
org = "myorg"
}
# per-service SKUs; lookup falls back to "Standard" if service is absent
skus = { orders = "Premium", billing = "Standard" }
orders_sku = lookup(local.skus, "orders", "Standard")
}
resource "azurerm_storage_account" "tfstate" {
name = "myorgtfstatedev"
resource_group_name = azurerm_resource_group.main.name
location = "westus2"
account_tier = "Standard"
account_replication_type = coalesce(var.replication, "LRS") # override or LRS
# base tags + a per-resource tag; "tier" is added, base keys preserved
tags = merge(local.base_tags, { tier = "state" })
}
Functions are the whole toolbox
There is no way to define your own functions in Terraform — you compose the built-ins. Skim the categories once: string (format, join, split, replace), collection (merge, lookup, concat, flatten), and encoding (jsonencode, base64encode). Run experiments in terraform console — it evaluates any expression instantly.
Compose format + coalesce in TypeScript
Implement coalesce(...args) returning the first value that is not null, undefined or "". Then write resourceName(org, service, env, type) that returns "{org}-{service}-{env}-{type}". Build a name for org myorg, service orders, env coalesce(undefined, "dev"), type rg, and log it (expect myorg-orders-dev-rg).