Functions

Functions

A function transforms and combines values inside of expressions. Terraform has a large number of built-in functions1 — you cannot define your own.

Call a function with its name followed by arguments in parentheses:

name = upper("hello")   # "HELLO"

Functions are used inside expressions wherever values are needed:

main.tf
1
2
3
4
resource "local_file" "inventory" {
  filename = "inventory.txt"
  content  = join("\n", ["web-1", "web-2", "db-1"])
}

A few commonly used functions from different categories:

FunctionExampleResult
upperupper("hello")"HELLO"
formatformat("app-%s", "eu")"app-eu"
joinjoin("-", ["a", "b"])"a-b"
lengthlength(["a", "b", "c"])3
concatconcat([1, 2], [3])[1, 2, 3]
filefile("notes.txt")contents of notes.txt
tosettoset(["a", "a", "b"])["a", "b"]

Functions can be nested — the result of one function becomes the argument of another:

name = format("app-%s", lower(trimspace(" EU ")))   # "app-eu"
Use terraform console to experiment with functions interactively. Type an expression such as join("-", ["a", "b"]) and see its result immediately.

Best practices

  • Keep expressions readable — break deeply nested function calls into intermediate local values with descriptive names.
  • Check whether a built-in function already does what you need before combining several functions to reimplement it.
  • Use terraform console to test expressions before putting them in your configuration.

  1. The full list is available in the Terraform documentation. Functions are grouped into categories such as string, numeric, collection, filesystem, date and time, and encoding functions. ↩︎