Chapter 10: Commonly used functions in Terraform

Built-in Terraform Functions

Terraform has many built-in functions that make our lives easier when writing code. Here are some of them.

A complete list of functions can be found in the official documentation.

lower / upper: Returns the lowercase/uppercase version of a string.

lower("Hello World")  # returns "hello world"
upper("Hello World")  # returns "HELLO WORLD"

min / max: Returns the minimum/maximum value in a list of numbers.

min(1, 3, 2, 5)  # returns 1
max(1, 3, 2, 5)  # returns 5

length: Returns the number of elements in a list.

length([1, 2, 3])  # returns 3

lookup(map, key, default): Retrieves a value from a map (also known as an object or dictionary) based on a given key. If the key is present in the map, the function returns the associated value. If the key is not present in the map, the function returns a default value that you specify.

locals {
  allowed_sizes = {
    "dev"   = "Standard_B1ms"
    "test"  = "Standard_B2ms"
    "prod"  = "Standard_D2s_v3"
  }
}

resource "azurerm_virtual_machine" "vm" {
  name  = "myvm"
  size  = lookup(local.allowed_sizes, var.environment, "Standard_B1ms")
  # other arguments omitted
}

join(delimiter, list): Returns a string that is the elements of a list joined together, separated by a delimiter.

merge(maps): Returns a new map that is the combination of multiple maps. If the same key is present in multiple maps, the value from the last map will be used.

toset(list): Converts a list to a set, which is a data type that represents an unordered collection of unique values.

tomap(list): Converts a list of key-value pairs to a map. For example:

contains(list, element): Returns a Boolean value indicating whether a given element is in a list.

coalesce(values): Returns the first non-null value in a list of values. For example:

flatten(list): Flattens a list of lists into a single list. For example:

try(expression): Evaluates an expression and returns the result, or a default value if the expression produces an error. For example:

How to Test Variables in Terraform?

If you are writing your own Terraform code, it is likely that you will encounter issues that require you to test a variable. For example, you may want to see the result that a map function returns. In this case, you can use the terraform console command for this purpose.

In Terraform console, you cannot define new variables. Instead, you must reference existing variables or provide them using the -var flag when running the terraform console command. Alternatively, you can use the -var-file flag to pass a complete variable file.

Last updated