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
In a nutshell
  • sort is lexical on strings, so "10" comes before "2".
  • concat keeps duplicates; add distinct to remove them.
  • merge lets the later argument win, and lookup returns 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.

Input valuesInner function firstOuter functionFinal valueArgument or condition

How it works

Function results to know

ExpressionResult
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)]...)
}
  1. values(local.teams) gives [["web", "api"], ["api", "log"]], in key order.
  2. flatten gives ["web", "api", "api", "log"].
  3. distinct gives ["web", "api", "log"].
  4. sort gives ["api", "log", "web"], which is local.services.
  5. local.names is ["svc-api", "svc-log", "svc-web"].
  6. The inner list in largest is [2, 2], so max(2, 2) is 2.

for expressions and references

FormExampleProduces
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

ArgumentEffect
create_before_destroyThe replacement is created first
prevent_destroyA plan that would destroy the object fails
ignore_changesListed attributes are ignored on updates; on create the configuration values are used
replace_triggered_byReplaces this resource when a referenced item changes

Custom conditions

BlockWhen it runsOn failureTypical use
Variable validationFirst, before a plan is builtStops the runBad input
preconditionBefore the object is acted onStops the runAn assumption about other objects
postconditionAfter planning and applying, or after a data source readStops dependent actions, no rollbackA guarantee about the result, using self
check with assertLast step of plan or applyWarning onlyOngoing 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

  • sort is lexical on strings, so "10" comes before "2".
  • concat keeps duplicates; add distinct to remove them.
  • merge lets the later argument win, and lookup returns its default for a missing key.
  • max and min take numbers as separate arguments, so a list needs ....
  • Only check blocks continue after failure; a failed postcondition does not undo what was applied.
  • ignore_changes does not affect creation.
Watch out

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"], because sort compares strings by Unicode code point and 1 comes before 9.

  • 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 check block. Its failed assert reports 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.