4.4.3. Built-in Functions
💡 First Principle: Functions are pure transformations of values — given the same inputs they return the same output with no side effects — which is why they're safe to use anywhere in configuration and why Terraform can evaluate them during planning.
Terraform ships a large library of built-in functions across categories: numeric (min, max, abs), string (upper, lower, format, join, split, replace), collection (length, lookup, merge, concat, flatten, keys, values), encoding (jsonencode, base64encode), filesystem (file, templatefile), type conversion (tostring, tonumber, toset, tolist), and more. You can experiment with any of them interactively in terraform console.
A few behaviors are worth knowing precisely:
| Function | Behavior |
|---|---|
merge(m1, m2, ...) | Combines maps; when a key appears in several, the later argument wins |
lookup(map, key, default) | Returns default when the key is absent instead of failing |
flatten(list) | Removes every level of list nesting, not just one |
format(spec, ...) | printf-style building: %s a string, %d a number, %02d zero-padded to two digits |
Newer Terraform versions also support provider-defined functions — functions contributed by a provider and called as provider::name::function(...). But core itself still has no mechanism for you to define your own general-purpose functions.
⚠️ Exam Trap: The classic fact: Terraform does not support user-defined (custom) functions in core — you compose built-ins (and, in recent versions, provider-defined functions). Also remember terraform console is the tool for testing expressions and functions without applying anything.
Reflection Question: Why is terraform console a safe way to learn a function's behavior, given everything you know about which commands change infrastructure?