Grafvision - Fotolia
Walk through common use cases for built-in Terraform functions
Follow along with this Terraform tutorial to learn and apply various types of built-in functions -- including Numeric, String, and Date and Time -- within the IaC tool.
IT teams can use HashiCorp's Terraform, an infrastructure-as-code tool, to deploy and manage cloud and on-premises resources. To optimize the tool's use, learn and install Terraform functions.
Admins can use built-in Terraform functions to perform various mathematical computations related to a deployment and to perform operations, such as to encode and decode, or to capture and display timestamps. The Terraform language only supports the functions built into it; custom or user-defined functions are not available.
Use this Terraform tutorial to walk through the basics of functions, as well as some common uses for them in enterprise deployments.
Start with the syntax
The syntax for a Terraform function starts with the function name, followed by parentheses that contain zero to multiple comma-separated arguments:
name(arg-1, arg-2, … arg-n)
For example, to capture a timestamp, use the timestamp() function to see the current date and time:
> timestamp()
2019-12-07T07:44:12Z
To read contents from a file at a given path, and have those contents returned as a string, use the file() function and provide the path to the file as an argument:
Interpolation support for Terraform functions
The Terraform configuration language supports interpolation, which enables admins to pass functions as a string to perform a variety of operations. These interpolations are wrapped in the special syntax ${ builtinfunction() } as demonstrated in following example:
resource "myinstance" "web" {
tags = ["${var.env == "prod" ? var.prod_subnet : var.dev_subnet}"]
}
Use the Terraform console to observe interpolation and various functions in action. To apply a configuration file in Terraform, use the above-mentioned interpolation syntax to reference variables and resources, and to call some built-in functions.
Let's take a look at an example. In this Terraform tutorial, we have variables named 'environment,' and will map various environments -- such as testing and production -- to AWS availability zones (AZs). Use another variable, named 'availzone,' to map these zones to AZs such as 'us-east-1a,' 'us-east-1b' and 'us-east-1c.' These are comma-separated values, as you can see below:
variable "environment" {
default = {
"test" = "us-east-1"
"prod" = "us-west-2"
}
}
variable "availzone" {
description = "Availability Zones Mapping"
default = {
"us-east-1" = "us-east-1a,us-east-1b,us-east-1c"
"us-west-2" = "us-west-2a,us-west-2b,us-east-1c"
}
}
To capture one AZ, first use the lookup()function to get the list of comma-separated values, and then split it with a comma ( ,) and the split() function. Finally, use the element() function to capture the defined index of choice. This will return an AZ as a string. Place all these functions inside ${ }, as shown below, so that the Terraform configuration language understands that these functions must be interpolated before deployment.
output "availabiltyzones" {
value = "${element(split(",", lookup(var.availzone,var.environment.prod)), 1)}"
}
Taken together, the above steps would look as follows:
List of built-in Terraform functions
Terraform functions can be classified in one of the following categories, depending on their use case.
Numeric functions
These functions perform numerical operations, such as calculating the maximum, minimum, power/exponent and logarithm, as demonstrated in following example:
String functions
The Terraform language also provides built-in functions to manipulate strings. For example, title(), lower() and upper() functions change the case of input strings:
IT teams can also split a string, join two or more strings, and replace a substring with another:
Date and Time functions
Date and Time functions are useful to capture and display timestamps when a Terraform configuration is applied. As we saw in an earlier example, the built-in function, timestamp(), returns the date and time:
Use the built-in function formatdate() to arrange the date and time in a more convenient format:
Encoding functions
Terraform has a few built-in functions that perform encoding and decoding on a string. For example, the base64encode('string') function returns Base64-encoded string, which is useful to deploy Azure resources that accept Base64-encoded custom scripts for the setup of VMs. In the example below, the file() function returns the content of a script in plain text, which is then encoded by the Base64encode() function and fed to the script attribute of the resource:
resource "azurerm_virtual_machine_extension" "Example" { name = "MyVM" location = "${azurerm_resource_group.test.location}" resource_group_name = "${azurerm_resource_group.test.name}" virtual_machine_name = "${azurerm_virtual_machine.test.name}" publisher = "Microsoft.Azure.Extensions" type = "CustomScript" type_handler_version = "2.0" settings = <
Collections functions
Some built-in Terraform functions perform multiple operations, such as determining the length of a list or string, on collections of values:
length([1,12,31,14,5,2])
length("this is a string")
You can also limit the return to only find distinct elements in a list, or search a list for a specific item: