🎓 A1Learner
🔍
0 of 50 lessons completed

Functions

Functions are small built-in tools that change a value into another value. Terraform calls them inside expressions, wherever a value is needed.

format builds a name

format fills each placeholder with a value in order. The result is one string.

locals {
  name = format("%s-%s", "app", "dev")
}

output "name" {
  value = local.name
}

join links a list

join puts a separator between each item in a list. The result is one string.

locals {
  tags = join(", ", ["web", "api", "db"])
}

output "tags" {
  value = local.tags
}

lookup reads a map

lookup returns the value for a key. A default value covers a missing key.

locals {
  sizes = {
    small = "t3.micro"
    large = "t3.large"
  }
  size = lookup(local.sizes, "small", "t3.micro")
}

output "size" {
  value = local.size
}

upper and lower change case

upper makes every letter capital. lower makes every letter small.

locals {
  loud  = upper("hello")
  quiet = lower("HELLO")
}

output "loud" {
  value = local.loud
}

output "quiet" {
  value = local.quiet
}

Example

variable "environment" {
  type    = string
  default = "dev"
}

locals {
  parts = ["app", var.environment, "main"]
  name  = join("-", local.parts)
  label = format("Name: %s", upper(local.name))
  sizes = {
    dev  = "small"
    prod = "large"
  }
  size = lookup(local.sizes, var.environment, "small")
}

resource "local_file" "summary" {
  content  = "${local.label} uses size ${local.size}."
  filename = "${path.module}/summary.txt"
}

output "label" {
  value = local.label
}

output "size" {
  value = local.size
}

Key points

  • A function takes inputs and returns a result.
  • Functions do not create resources.
  • format fills in a pattern with values to make one string.
  • join turns a list into one string with a separator.
  • lookup reads a value from a map by its key.
  • String functions such as upper and lower change the case of text.

join builds the name from three parts. format and upper turn it into a label. lookup picks the size for the environment, with small as the safe default.

Note

Every function is listed in the Terraform language documentation, with its exact inputs.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

What does join(", ", ["a", "b"]) return?