Lesson 3 of 3 Expressions and Functions

Built-in Functions and terraform console

Terraform includes a library of built-in functions for transforming values. This lesson describes the function categories, the functions that appear most often and how to test them with terraform console.

Learning outcomes

After completing this lesson, you will be able to:

  • Identify the categories of built-in functions and frequently used functions.
  • Explain the behaviour of common functions such as lookup, merge and cidrsubnet.
  • Describe how terraform console evaluates expressions.

Calling functions

A function call has the form NAME(ARG1, ARG2, ...), as in max(5, 12, 9) or upper(var.name). Terraform has a fixed set of built-in functions and does not support user-defined functions. Since Terraform 1.8, providers can contribute functions, called with a prefix such as provider::aws::arn_parse(var.role_arn). The argument expansion symbol ... passes a list as separate arguments: min(var.sizes...).

Function categories

HashiCorp groups the built-in functions into categories. The following table lists each category with functions that commonly appear in configurations and exam questions.

CategoryCommon functions
Numericabs, ceil, floor, max, min, pow, parseint
Stringformat, join, split, lower, upper, replace, substr, trimspace, regex, startswith
Collectionlength, lookup, merge, concat, flatten, keys, values, contains, element, zipmap, distinct, slice
Encodingjsonencode, jsondecode, yamlencode, base64encode, base64decode, csvdecode
Filesystemfile, fileexists, fileset, templatefile, abspath
Date and timetimestamp, timeadd, formatdate, plantimestamp
Hash and cryptosha256, md5, filesha256, uuid, bcrypt
IP networkcidrsubnet, cidrhost, cidrnetmask
Type conversiontostring, tonumber, tolist, toset, tomap, try, can, sensitive, nonsensitive
Sort into groups

Function categories

Exam skills 4.5.3

Sort functions into the categories HashiCorp uses.

Log in to try this activity Interactive activities are free with an account.

Functions to know well

A few functions are used so often that their behaviour is worth memorising.

  • lookup(map, key, default) returns the value for a key, or the default if the key is missing.
  • merge(map1, map2) combines maps; for duplicate keys, the later map wins.
  • concat(list1, list2) joins lists; flatten(list_of_lists) removes one or more levels of nesting.
  • join(",", list) and split(",", string) convert between lists and delimited strings.
  • cidrsubnet("10.0.0.0/16", 8, 2) returns 10.0.2.0/24: it adds 8 bits to the prefix and selects subnet number 2.
  • file(path) reads a file as a string; templatefile(path, vars) renders a template.
  • try(expr1, expr2) returns the first expression that evaluates without error; can(expr) returns true if the expression evaluates without error, which suits validation conditions.
  • jsonencode(value) turns a Terraform value into JSON, for example for an IAM policy.

Functions are evaluated during planning where their inputs are known. Functions such as timestamp() and uuid() return a new value on every run, so using them in resource arguments causes a change on every plan.

The following diagram compares the two argument orders of merge.

How merge resolves duplicate keys. Later maps win, so merge(local.default_tags, var.tags) lets a caller's Owner override the default while ManagedBy remains. Reversing the arguments lets the defaults overwrite the caller's values. terraform console confirms the result before committing.
The tags are illustrative.
Fill in the number

Evaluate the function

Exam skills 4.5.3

Work out what common built-in functions return.

Log in to try this activity Interactive activities are free with an account.

Testing with terraform console

terraform console opens an interactive prompt that evaluates expressions using the current configuration's variables and locals and the values in state. It is the quickest way to check what a function or expression returns.

$ terraform console
> cidrsubnet("10.0.0.0/16", 8, 2)
"10.0.2.0/24"
> merge({ a = 1, b = 2 }, { b = 3 })
{
  "a" = 1
  "b" = 3
}
> [for s in ["web", "api"] : upper(s)]
[
  "WEB",
  "API",
]
> exit

The console takes a state lock while it runs when the backend supports locking, and it does not change anything. Expressions can also be piped in, as in echo 'max(1, 5)' | terraform console, which is handy in scripts.

True or false

terraform console

Exam skills 4.5.3

Check what terraform console can do.

Log in to try this activity Interactive activities are free with an account.
Worked example

Merging tags

A module adds default tags { ManagedBy = "terraform", Owner = "platform" } to every resource, but callers must be able to override Owner. Which expression should the module use?

The decisive behaviour is how merge handles duplicate keys.

merge(local.default_tags, var.tags) puts the caller's map last, so a caller who passes { Owner = "payments" } overrides the default Owner while ManagedBy remains. Reversing the arguments would let the defaults overwrite the caller's values. Checking the result in terraform console before committing confirms the behaviour.

Check yourself

What does lookup({ a = 1 }, "b", 0) return?

Show answer

0, the default, because the key b is not in the map.

Exam Tips

Remember for the exam

  • No user-defined functions; providers can add provider::NAME::FUNC functions.
  • lookup defaults, merge's last-wins rule, flatten, cidrsubnet, try and can are frequent.
  • terraform console evaluates expressions against current state.
  • timestamp() and uuid() change on every run.