Scalable Terraform Configuration Design · Topic 3 of 4
Functions and Advanced Configurations
Terraform Professional 002: predict results from merge, lookup, one, flatten and for expressions, then use dynamic blocks, lifecycle and conditions.
- 5 min
sortis lexical on strings, so"10"comes before"2".concatkeeps duplicates; adddistinctto remove them.mergelets the later argument win, andlookupreturns its default for a missing key.
What it is
Function questions give you an expression and ask for its exact value, including whether it errors. HashiCorp names the ones to study: max, min, one, sort, concat, format, join, merge, lookup, distinct, flatten and length, plus for expressions and references to values.
Advanced configuration means the constructs that make code respond to data: conditionals, for expressions, splats, dynamic blocks, lifecycle rules and custom conditions.
How it works
Function results to know
| Expression | Result |
|---|---|
max(3, 7, 2) | 7 |
min([3, 7, 2]...) | 2, because ... expands the list |
one([]) | null |
one(["a"]) | "a" |
one(["a", "b"]) | Error, more than one element |
sort(["b", "10", "2"]) | ["10", "2", "b"], lexical and not numeric |
concat(["a"], ["b", "a"]) | ["a", "b", "a"], keeps duplicates |
distinct(["a", "b", "a"]) | ["a", "b"], first occurrences in order |
format("%s-%03d", "web", 7) | "web-007" |
join("-", ["a", "b"]) | "a-b" |
merge({ a = 1, b = 2 }, { b = 3 }) | { a = 1, b = 3 }, the later argument wins |
lookup({ a = 1 }, "z", 0) | 0, the default for a missing key |
flatten([["a"], [], ["b", ["c"]]]) | ["a", "b", "c"], all nesting removed |
length({ a = 1, b = 2 }) | 2; also works on lists and strings |
merge takes maps as separate arguments, while join takes a separator and lists of strings. The + operator does not combine maps.
Walkthrough: evaluate from the inside out
locals {
teams = {
app = ["web", "api"]
ops = ["api", "log"]
}
services = sort(distinct(flatten(values(local.teams))))
names = [for s in local.services : format("svc-%s", s)]
largest = max([for t in values(local.teams) : length(t)]...)
}
values(local.teams)gives[["web", "api"], ["api", "log"]], in key order.flattengives["web", "api", "api", "log"].distinctgives["web", "api", "log"].sortgives["api", "log", "web"], which islocal.services.local.namesis["svc-api", "svc-log", "svc-web"].- The inner list in
largestis[2, 2], somax(2, 2)is2.
for expressions and references
| Form | Example | Produces |
|---|---|---|
| List | [for s in var.names : upper(s)] | Tuple |
| Map | { for s in var.names : s => length(s) } | Object |
| Filter | [for s in var.names : s if s != "tmp"] | Tuple without tmp |
| Group | { for u in var.users : u.team => u.name... } | Object of lists per team |
A for over a map reads items in key order, not in the order written. Named values use prefixes: var., local., module., data., plus each., count.index, self and path.module in their own contexts.
Dynamic blocks and conditionals
resource "aws_security_group" "web" {
dynamic "ingress" {
for_each = var.ports
content {
from_port = ingress.value
to_port = ingress.value
protocol = "tcp"
cidr_blocks = ["10.0.0.0/8"]
}
}
}
dynamic repeats a nested block, never a resource. The iterator takes the block label, here ingress, unless you set iterator.
var.enabled ? 1 : 0 with count is the common switch. Then aws_instance.x[*].id gives a list of zero or one item, and one(aws_instance.x[*].id) turns it into a value or null.
Lifecycle arguments
| Argument | Effect |
|---|---|
create_before_destroy | The replacement is created first |
prevent_destroy | A plan that would destroy the object fails |
ignore_changes | Listed attributes are ignored on updates; on create the configuration values are used |
replace_triggered_by | Replaces this resource when a referenced item changes |
Custom conditions
| Block | When it runs | On failure | Typical use |
|---|---|---|---|
Variable validation | First, before a plan is built | Stops the run | Bad input |
precondition | Before the object is acted on | Stops the run | An assumption about other objects |
postcondition | After planning and applying, or after a data source read | Stops dependent actions, no rollback | A guarantee about the result, using self |
check with assert | Last step of plan or apply | Warning only | Ongoing health checks |
check "site_up" {
data "http" "site" {
url = "https://example.com/health"
}
assert {
condition = data.http.site.status_code == 200
error_message = "Health endpoint is not returning 200."
}
}
How the exam asks about this
- "Combine two tag maps where one set must take priority." Use merge, with the priority map as the last argument.
- "A list may have zero or one element and you need a single value." Use one(), which errors on two or more.
- "Report a failed health check without blocking the apply." Use a check block, because it only warns.
What to remember for the exam
sortis lexical on strings, so"10"comes before"2".concatkeeps duplicates; adddistinctto remove them.mergelets the later argument win, andlookupreturns its default for a missing key.maxandmintake numbers as separate arguments, so a list needs....- Only
checkblocks continue after failure; a failedpostconditiondoes not undo what was applied. ignore_changesdoes not affect creation.
one() is not "first element". With two or more elements it returns an error, which is often the behavior the question is testing.
Common mistakes
Reading a function result without its type. join returns a string and concat returns a list. Options often differ only in that detail, so check the shape as well as the content.
Expecting a postcondition to roll back. Terraform may already have made the change when it runs. The failure stops later dependent work and leaves the object in place.
Using dynamic to repeat a resource. It generates nested blocks only. Use for_each or count on the resource for whole objects.
Check yourself
What does
sort(["9", "10"])return?["10", "9"], becausesortcompares strings by Unicode code point and1comes before9.What is
merge({ env = "dev" }, { env = "prod", app = "web" })?{ env = "prod", app = "web" }. When a key repeats, the value from the later argument wins.Which condition block lets the apply continue after a failure?
The
checkblock. Its failedassertreports a warning, while validations, preconditions and postconditions stop the operation.
Topic 3 of 4 in Scalable Terraform Configuration Design
Test yourself on Scalable Terraform Configuration Design
The full HashiCorp Terraform Infrastructure Engineer Professional question bank has 600 questions, with timed practice exams and an explanation for every answer.
This study guide is independent and is not affiliated with, endorsed by, or sponsored by HashiCorp. Vendor names, certification names and exam codes are trademarks of their respective owners and are used for identification only.