Planfile

Terraform functions: a practical guide with examples

Updated

Terraform has built-in functions you call inside expressions, like upper("prod") or cidrsubnet("10.0.0.0/16", 8, 3), which returns "10.0.3.0/24". They cover strings, collections, numbers, encoding, files, IP networks and type conversion. You can't define your own, but since Terraform 1.8 providers can add functions. Use terraform console to try any function against your configuration and state.

terraform console evaluating cidrsubnet("10.0.0.0/16", 8, 3) to "10.0.3.0/24" and upper("prod") to "PROD"
terraform console evaluates functions against your configuration.

How Terraform functions work

Terraform's expression language has a fixed set of built-in functions. You call them by name with arguments in parentheses, anywhere an expression is allowed: resource arguments, locals, outputs, conditions.

locals {
  name    = lower(trimspace(var.project))
  subnets = [for i in range(3) : cidrsubnet(var.vpc_cidr, 8, i)]
  tags    = merge(var.default_tags, { Name = upper(local.name) })
}

Three facts worth knowing up front:

The fastest way to learn them is terraform console, covered at the end of this page. The examples below show results the way the console prints them.

String functions

FunctionExampleResult
formatformat("%s-%03d", "web", 7)"web-007"
joinjoin("-", ["foo", "bar", "baz"])"foo-bar-baz"
splitsplit(",", "foo,bar,baz")tolist(["foo", "bar", "baz"])
replacereplace("1 + 2 + 3", "+", "-")"1 - 2 - 3"
replace (regex)replace("hello world", "/w.*d/", "everybody")"hello everybody"
upperupper("prod")"PROD"
lowerlower("ACME")"acme"
trimspacetrimspace(" web ")"web"

Terraform string replace: replace(string, search, replacement) replaces every occurrence of a literal substring. Wrap the search in slashes to use a regular expression instead, as in the second row. format uses printf-style verbs (%s string, %d integer, %03d zero-padded to three digits); formatlist does the same for each element of a list.

For most string building, interpolation is simpler than a function: "acme-${var.env}-logs". Use format when you need padding or a reusable pattern, and join to turn a list into one string.

Collection functions: merge, lookup, zipmap and more

FunctionExampleResult
lengthlength(["a", "b"])2
mergemerge({a = "b", c = "d"}, {e = "f", c = "z"}){ a = "b", c = "z", e = "f" }
lookuplookup({a = "ay", b = "bee"}, "c", "what?")"what?"
keyskeys({a = 1, c = 2, d = 3})["a", "c", "d"]
valuesvalues({a = 3, c = 2, d = 1})[3, 2, 1]
zipmapzipmap(["a", "b"], [1, 2]){ a = 1, b = 2 }
flattenflatten([["a", "b"], [], ["c"]])["a", "b", "c"]
concatconcat(["a", ""], ["b", "c"])["a", "", "b", "c"]
containscontains(["a", "b", "c"], "a")true
tosettoset(["a", "b", "c", "b"])toset(["a", "b", "c"])

Numeric, encoding and filesystem functions

FunctionExampleResult
minmin(12, 54, 3)3
maxmax(12, 54, 3)54
max (list)max([12, 54, 3]...)54
jsonencodejsonencode({"hello" = "world"})"{\"hello\":\"world\"}"
base64encodebase64encode("Hello World")"SGVsbG8gV29ybGQ="

min and max take separate arguments; to pass a list, expand it with .... jsonencode turns any Terraform value into a JSON string, which is the clean way to write IAM policies and other JSON documents instead of heredocs (its counterpart jsondecode parses JSON). yamlencode and yamldecode do the same for YAML.

resource "aws_iam_policy" "read_logs" {
  name = "read-logs"
  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Effect   = "Allow"
      Action   = ["s3:GetObject"]
      Resource = "${aws_s3_bucket.logs.arn}/*"
    }]
  })
}

Filesystem functions read files at plan time, relative to a path you give. Use path.module so the path works wherever the module is called from. file reads a file as a string; templatefile renders a template with variables, including for and if directives:

# backends.tftpl
%{ for addr in ip_addrs ~}
backend ${addr}:${port}
%{ endfor ~}

# main.tf
locals {
  config = templatefile("${path.module}/backends.tftpl", {
    port     = 8080
    ip_addrs = ["10.0.0.1", "10.0.0.2"]
  })
}
# local.config is "backend 10.0.0.1:8080\nbackend 10.0.0.2:8080\n"

These functions only read files that exist before Terraform runs; they can't read a file that a resource creates during the same apply.

IP network functions: cidrsubnet and cidrhost

FunctionExampleResult
cidrsubnetcidrsubnet("10.0.0.0/16", 8, 3)"10.0.3.0/24"
cidrsubnetcidrsubnet("172.16.0.0/12", 4, 2)"172.18.0.0/16"
cidrhostcidrhost("10.12.112.0/20", 16)"10.12.112.16"

Terraform cidrsubnet takes a prefix, a number of bits to add to the mask, and a network number. In cidrsubnet("10.0.0.0/16", 8, 3), adding 8 bits to /16 gives /24 subnets, and number 3 is the fourth of them (counting from 0): 10.0.3.0/24. Combine it with count.index to carve a VPC into subnets without typing ranges:

resource "aws_subnet" "private" {
  count      = 3
  vpc_id     = aws_vpc.main.id
  cidr_block = cidrsubnet(aws_vpc.main.cidr_block, 8, count.index)
  # 10.0.0.0/24, 10.0.1.0/24, 10.0.2.0/24 for a 10.0.0.0/16 VPC
}

cidrhost(prefix, n) returns the n-th address in a range, handy for fixed private IPs. cidrsubnets (plural) allocates several consecutive subnets of different sizes in one call.

Type conversion and error handling: try, can, tostring

Don't use try to hide real mistakes: it catches every error in the expression, including typos in attribute names.

Provider-defined functions

Since Terraform 1.8, providers can ship their own functions. You call them with the provider:: prefix, the provider's local name from required_providers, and the function name:

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = ">= 5.40"
    }
  }
}

output "account_id" {
  value = provider::aws::arn_parse(aws_s3_bucket.logs.arn).account_id
}

The provider must be declared in required_providers, and the provider version must include the function (the AWS provider added its first functions, such as arn_parse, in 5.40). Each provider's functions are listed in its documentation on the Terraform Registry.

terraform console: try functions interactively

terraform console opens an interactive prompt that evaluates expressions against your configuration and current state. It's the quickest way to check what a function returns before you put it in code:

$ terraform console
> cidrsubnet("10.0.0.0/16", 8, 3)
"10.0.3.0/24"
> upper("prod")
"PROD"
> var.env
"dev"
> aws_s3_bucket.logs.arn
"arn:aws:s3:::acme-dev-logs"
> exit

Common errors

Try it in a Lab

Planfile's chapter Functions and expressions has a console built into the Lab. In Work it out in the console you find the fourth /24 of 10.0.0.0/16 with cidrsubnet and turn it into an output; Default tags with merge and Carve the subnets put merge() and cidrsubnet() with count.index to work in real configurations.

Questions

Can I create custom functions in Terraform?

No. Terraform only has built-in functions and, since 1.8, functions provided by providers. Use locals to name repeated expressions and modules to reuse blocks of configuration.

What does cidrsubnet do in Terraform?

It calculates a subnet inside a network prefix. cidrsubnet("10.0.0.0/16", 8, 3) adds 8 bits to the /16 mask and returns the fourth /24: "10.0.3.0/24".

What is the difference between merge and concat?

merge combines maps or objects, with later arguments overriding earlier keys. concat joins lists into one list.

How do I exit terraform console?

Type exit or press Ctrl-C or Ctrl-D.

How do I replace a string in Terraform?

Use replace(string, search, replacement), which replaces every occurrence. Put the search term between slashes, such as "/[0-9]+/", to match a regular expression.

What does lookup do in Terraform?

lookup(map, key, default) returns the value for key, or the default if the key is missing. Always pass a default; without one a missing key is an error.