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.

join(",", ["a", "b", "c"])  # returns "a,b,c"

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.

merge({a = 1, b = 2}, {b = 3, c = 4})  # returns {a = 1, b = 3, c = 4}

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

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

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

tomap({"a" = 1, "b" = 2})  # returns {a = 1, b = 2}

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

contains(["a", "b", "c"], "b")  # returns true
contains(["a", "b", "c"], "d")  # returns false

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

coalesce(null, "", "a", "b")  # returns "a"

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

flatten([[1, 2], [3, 4], [5]])  # returns [1, 2, 3, 4, 5]

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

locals {
  vm_attributes = {
    vm_size = "Standard_B1ms"
    vm_name = "testvm001"
  }
}

try(local.vm_attributes.vm_size, "donotexist")  # returns "Standard_B1ms"
try(local.vm_attributes.vm_size2, "donotexist")  # returns "donotexist"

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.

> terraform console
> var.mymap
tomap({
  "key" = {
    "test1" = "value1"
    "test2" = tomap({
      "key" = {
        "nested1" = "nestedvalue1"
        "nested2" = "nestedvalue2"
      }
    })
  }
})
> 
# Then you can try merging your variable with other or custom variable
> merge({ a = "aaa" }, var.mymap)
{
  "a" = "aaa"
  "key" = {
    "test1" = "value1"
    "test2" = tomap({
      "key" = {
        "nested1" = "nestedvalue1"
        "nested2" = "nestedvalue2"
      }
    })
  }
}
>  

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