Built-in functions in practice

Intermediate · 7 min

The handful of Terraform functions that do most of the work, merge, lookup, flatten, cidrsubnet and more, and how to test each safely in terraform console.

Before thisConditionals and for expressions

DevOps with Flavius · 7 min

Built-in functions in practice

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by DevOps with FlaviusReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Terraform has a fixed set of built-in functions and you cannot define your own. Providers can contribute functions since Terraform 1.8, called as `provider::name::function()`.
  • A few do most of the work: `merge` for maps, `lookup` and `try` for safe access, `flatten` for nested lists, `toset` for `for_each`, `format` and `replace` for text.
  • `cidrsubnet(prefix, newbits, num)` carves the num-th subnet with `newbits` more bits out of a network, so you compute addresses instead of typing them.
  • `terraform console` evaluates an expression against your configuration without applying anything. Use it before putting a function in a resource.

Do not compute subnets by hand

A network design says the VPC is 10.0.0.0/16, with a /24 for each of three zones in public and again in private. Six CIDR strings, typed out. Then someone changes the VPC range and has to retype six, and one gets a typo that overlaps another. The error arrives at apply, as a vague API refusal.

Functions let you write the rule, “carve /24s out of the VPC range”, and have the computer produce the strings. Terraform ships with a fixed library for this, which is bigger than people use. You can learn the working set in an afternoon.

What you get and what you do not

The functions are built into the language. You cannot define your own in HCL, which is deliberate. The v1.8 changelog added a way around this for provider authors: providers can offer functions, called as provider::provider_name::function_name(). OpenTofu’s changelog mentions provider functions in its 1.7 series as well. Ordinary configurations will use the built-ins.

The groups to know are string (format, replace, join, split, lower), collection (merge, lookup, flatten, toset, keys, values, length, concat), type conversion (tostring, tonumber, tolist), encoding (jsonencode, yamlencode, base64encode), file (file, templatefile), IP network (cidrsubnet, cidrhost) and hash functions. try and can handle errors.

The ones I reach for

merge(a, b) combines maps and later arguments win on a collision. It is the standard way to layer tags: merge(local.common_tags, { Name = "api" }).

lookup(map, key, default) reads a map with a fallback. try(expr, fallback) evaluates an expression and returns the fallback if it errors, which makes optional nested attributes manageable.

flatten(list) collapses nested lists into one. It is how you turn “for each environment, a list of subnets” into one flat list for for_each.

toset(list) converts a list to a set. for_each needs a set or map, so for_each = toset(var.names) is a line you will write often.

format("%s-%03d", name, i) is printf for strings, and replace(str, "-", "_") substitutes.

cidrsubnet(prefix, newbits, num) deserves its own section.

cidrsubnet, checked against the docs

The Terraform docs give three examples. I rebuilt the function with Python’s ipaddress module and ran those. It is my own re-implementation, not Terraform’s:

('172.16.0.0/12', 4, 2) -> 172.18.0.0/16
('10.1.2.0/24', 4, 15) -> 10.1.2.240/28
v6 -> fd00:fd12:3456:7800:a200::/72
one VPC /16 into /24s: ['10.0.0.0/24', '10.0.1.0/24', '10.0.2.0/24', '10.0.3.0/24']

The first three match the results printed in the docs: 172.18.0.0/16, 10.1.2.240/28 and fd00:fd12:3456:7800:a200::/72. The last line is the useful one. newbits is how many bits to add to the prefix, so /16 plus 8 gives /24, and num picks which of the 256 possible /24s. Number 0 is 10.0.0.0/24 and 3 is 10.0.3.0/24. In Terraform you would write this with count.index, or inside a for expression: cidrsubnet(var.vpc_cidr, 8, i).

One detail from my own run: the IPv6 docs example has host bits set in its prefix, fd00:fd12:3456:7890::/56. Python’s strict parser refused it until I told it not to be strict, while Terraform accepts it. So the real function is a little more forgiving than a textbook CIDR parser.

terraform console: your safe lab

terraform console opens a prompt that evaluates any expression against your configuration. It does not apply anything. In a project with variables and state it can read them, so you can type:

> cidrsubnet("10.0.0.0/16", 8, 2)
> merge({a = 1}, {b = 2})
> toset(["a", "b", "a"])

I could not run it here because there is no Terraform, so there is no transcript. The three lines are from the docs’ syntax. What I do is test every non-trivial function in the console first, and paste the working expression into the resource. It is the fastest feedback loop in the whole tool, and it removes most of the “apply to find out” habit. Sanabria’s command tour in deeper has a short console chapter.

Judgement

  • A function chain that needs a comment to explain is a candidate for a locals block with named steps.
  • Prefer lookup or try on user-supplied maps and try around anything that can legitimately be absent. Do not wrap everything in try, which hides real mistakes.
  • Impure functions such as timestamp() and uuid() change on every run. The for_each docs say they cannot be used to build keys. In general avoid them in resource arguments, or every plan shows a change.

About the video

The embed is all of DevOps with Flavius’s “7 Terraform Functions That Make Infrastructure Code Effortless”, July 2025, 7 minutes. Its chapters are merge(), lookup(), flatten(), cidrsubnet(), format(), toset() and replace(), each with a demo. It does not show terraform console or try, which is why those are in the lesson text and a deeper link. I judged the content from the chapter list. English was judged from title, channel and the English auto-caption track.

Where this fits

Now that you can compute values, you can make many of something. Next: count and for_each, and why the choice affects what happens when you delete one.

Check yourself

  1. 01You need to combine default tags with per-resource tags where the specific ones win. Which function?

    `merge(local.default_tags, var.extra_tags)`. When keys collide, later arguments win, so put the overrides last.

  2. 02What does `cidrsubnet("10.0.0.0/16", 8, 2)` return and why?

    `10.0.2.0/24`. Adding 8 bits to a /16 gives /24, and subnet number 2 is the third one. Number 0 is `10.0.0.0/24`, number 1 is `10.0.1.0/24`.

  3. 03How do you try a function without changing infrastructure?

    Run `terraform console` in the project and type the expression. It evaluates against your variables and, if state exists, your resources, and changes nothing.

  4. 04Why use `try()` or `lookup()` with a default instead of indexing a map directly?

    Direct indexing errors when the key is missing. `lookup(map, key, default)` and `try(expr, fallback)` let the configuration continue with a chosen fallback.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark