Understanding Terraform Functions Through Examples

Published by

on

Terraform is one of the most popular cloud development Infrastructure as Code (IaC) tools in the world due to its benefits — consistency, low risk, disaster recovery, and more. And with Terraform functions, talented developers like yourself can easily manage hundreds of services.

In this tutorial, you will learn how to build function parameters, call them, function scope, and a lot more!

Ready? Jump in and up your skills in provisioning infrastructure!

Table of Contents

Prerequisites

This tutorial comprises step-by-step demonstrations. To follow along, ensure you have the following in place:

  • A code editor – Any text editor works fine, but consider one that understands the HCL Terraform language, like Visual Studio (VS) Code.

Working with Numbers in Terraform Functions

Functions start you by creating modular code and reducing code duplication. Terraform does not support user-defined functions but only built-in ones, like numeric functions. For example, numeric functions let you find the maximum or minimum of two numbers.

To see the numeric functions in action, follow these steps:

  1. Open your terminal and run the below [terraform console](<https://developer.hashicorp.com/terraform/cli/commands/console>) command to access the Terraform console.
2.  terraform console

As shown below, you will notice you are working on the Terraform console once the prompt changes to >.

Accessing the Terraform console

  • Next, run the below abs() functions to return the absolute value of the given numbers**.**

If the number value is equal to or greater than zero (0), the function returns the absolute value of the number. Otherwise, if the number is less than zero (0), the function multiplies the number by a negative one (-1).

abs(12)      # Returns the absolute 12
abs(-12.34)  # Returns the absolute 12.34 (-12.34 * -1 = 12.34)
abs(0)       # Returns the absolute 0

Retrieving absolute values of specified numbers via the abs function

  • Besides the absolute value, run each of the below ceil() functions to retrieve the closest whole numbers that are greater than or equal to the given values.
5.  ceil(5)     # Returns absolute value 5
6.  ceil(5.1)   # Returns absolute value 6 (greater than 5.1)
7.  ceil(-4.3)  # Returns absolute value -4 (greater than -4.3)

Retrieving the closest whole number of values via the ceil function

  • Now, run the floor() functions below, which return the closest whole number less than or equal to the given value. Basically, the floor function works opposite to the ceil function.
9.  floor(3)    # Returns the absolute value of 3
10.floor(3.4)  # Returns the absolute value of 3 (less than 3.4)

Retrieving the closest whole number of values via the floor function

  1. Lastly, run each signum() function below to determine and return a value’s number sign. The signum() function lets you get an output as a positive or negative sign.
12.signum(-1)    # Returns -1 (negative)
13.signum(-344)  # Returns -1 (negative)
14.signum(11)    # Returns 1 (positive)

Below, you can see the functions returned -1 for negative numbers and 1 for positive.

Determining number signs via the signum function

Converting Code Formats via Terraform Encoding Functions

Keeping code consistent can be challenging, especially when you have lots of things going on in your code. Take the indentations and comments, for example.

How to keep your code neat without breaking sets of rules? Terraform Encoding functions will do the trick, allowing you to convert your code from one format to another.

<aside> 💡 There are many Encoding functions in Terraform, like [textencodebase64](<https://developer.hashicorp.com/terraform/language/functions/textencodebase64>), [yamlencode](<https://developer.hashicorp.com/terraform/language/functions/yamlencode>), and so on. But this tutorial only covers some of them.

</aside>

Related: Formatting Terraform Code With the Terraform fmt Command

Run the below encoding functions to convert each code to String to JSON format (jsondecode) and vice versa (jsonencode).

jsondecode("{\\"hello\\": \\"world\\"}") # Converts String into JSON format.
jsonencode({"hello"="world"})        # Converts JSON into String format.

Converting String to JSON format and vice versa

Now, run the following functions to convert String to YAML (yamlecode) and vice versa (yamlencode).

yamldecode("{\\"hello\\": \\"world\\"}")  # Converts String into YAML format.
yamlencode({"hello"="world"})         # Converts YAML into String format.

Converting String to YAML format and vice versa

Working the Filesystem with Terraform Functions

When writing scripts, you typically work with the filesystem. And what better way to interact with the filesystem than Terraform’s Filesystem functions? Filesystem functions in Terraform let you work with files stored in your filesystem.

<aside> 💡 Like the encoding functions, there are tons of Terraform Filesystem functions, such as [dirname](<https://developer.hashicorp.com/terraform/language/functions/dirname>), [pathexpand](<https://developer.hashicorp.com/terraform/language/functions/pathexpand>), and so on. But this tutorial can only cover some of them.

</aside>

To see how the Terraform Filesystem functions work:

  1. Run the below abspath() function to take a string containing a filesystem path ([path.root](<https://developer.hashicorp.com/terraform/language/expressions/references#path-root>)) and convert it to an absolute path. This function lets you retrieve the absolute path, a complete path, from the start of the actual filesystem of the current directory.
2.  abspath(path.root)

Below, the function converts the path.root to its absolute path of the current directory (/home/ubuntu).

Retrieving the absolute path of the working directory

  • Next, create a file called hello.txt with your preferred text editor in your working directory, add contents like “Hello World!” and save the file.

Once saved, run the below fileexists() function to check if the *hello.txt* file exists in the [path.module](<https://developer.hashicorp.com/terraform/language/expressions/references#path-module>) location.

fileexists("${path.module}/hello.txt")

If the file exists, you will get a true value response, as shown below. Otherwise, you will get a false response if the file is not found.

Checking if a file exists

  • Since the hello.txt file exists, run the following file() function to read, and return the contents of the file ("${path.module}/hello.txt") as a string.
5.  file("${path.module}/hello.txt")

Reading a file’s content

But if the file does not exist, you will get the following error instead.

Getting an error as the specified file does not exist

Manipulating Strings for Better Scripting

String manipulation is an essential skill for programmers to master. Why? Typically, you need to work with text and/or interact with the user in most applications. With these cases, the String functions will do the trick.

Related: Concatenate, Expand, Format and All Things PowerShell Strings

To see how String functions work, follow these steps:

  1. Run the below chomp() function to remove the newline characters at the end of a string.

This function can be useful if, for example, the function reads the string from a file with a newline character at the end.

chomp("hello\\n\\r")

Removing newline characters on a string

  • Next, run each function below to verify a string’s suffix (endswith) and prefix (startswith) and return a true or false value. These functions let you check conditions within the string, such as the last word or the first word.
3.  # Checks the string's suffix and returns either True or False
4.  endswith("hello world", "world") 
5.  # Checks the string's prefix and returns either True or False
6.  startswith("hello world", "hello") 

Verifying a string’s prefix and suffix

  • Now, run the below format() functions to format strings by substituting the values according to the declared variables. In many instances, you will be required to substitute the value rather than declare it at every place where format() functions play a vital role.

The following verbs function as follows:

  1. %s – Perform concatenation of strings together.
  2. %d – Performs conversion of integer numbers to decimal representation.
# Formats the string, placing "!" at the end.
format("Hello, %s!", "Adam")
# Formats the string and prints the result "There are 4 items".
format("There are %d items", 4) 
# Prints a list of strings by formatting values according to a specification string.
formatlist("Hello, %s!", ["AdamB", "AdamL", "Sagar", "Arman"]) 

Formatting strings for different output

<aside> 💡 Alternatively, instead of formatlist, run the below tolist function to convert an argument to a list value if you do not need any formatting: tolist(["AdamB", "AdamL", "Sagar", "Arman"])

</aside>

Converting an argument to a list value

  • After formatting strings, run the below join() function to concatenate multiple strings ("foo", "bar", "baz") together. The strings are joined but separated by commas (,) followed by a space character (or any separator you specify).

This function is useful when you have various lists of items to display as a single string.

join(", ", ["Adam", "Sagar", "Steve"])

Joining multiple strings

  • In contrast, run the split() function below to split one string ("foo,bar,baz” ) into multiple depending on the specified separator. In this case, the separator is a comma (,).
10.split(",", "Adam,Sagar,Steve") 

Splitting a single string to multiple

  1. Lastly, run the strrev function below to reverse the characters of a given string (hello).
12.strrev("hello")

Reversing a string

Converting Data Types from One Type to Another

There are multiple resource blocks in Terraform. In these resource blocks, you would typically use the input as the output of some dependent argument or values. In these cases, Type Conversion functions will come in handy in converting one data type to another.

  1. Run the following tobool() functions to convert arguments to Boolean values: true, false, and null.
2.  tobool(true)    # Converts a string into a Boolean value True.
3.  tobool("false") # Converts a string into a Boolean value False.
4.  tobool(null)    # Converts a null string into a Boolean value null.
5.  tobool("less")  # Attempts converting a string into a Boolean value (error).

Below, you can see each function converts arguments to Boolean values except the last one. Why? The tobool function only accepts the null value and the strings "true" and "false" to be converted to Boolean. All other values will produce an Invalid function argument error.

Converting strings to Boolean values

  • Now, run the below functions to verify operational arguments.

Besides converting strings to Boolean values, the tobool function also lets you verify operational arguments, like which number is greater or less.

tobool(2<1) # Determines if 2 is less than 1.
tobool(2>1) # Determines if 2 is greater than 1.

Verifying operational arguments

  • Finally, run the tostirng() functions below to convert arguments to strings.

This function is helpful since there are many functions in Terraform that only accept strings.

tostring(false) # Converts the returned value to a string ("false")
tostring(2>1)   # Converts the returned value to a string ("true")

Converting arguments to strings

Conclusion

In this tutorial, you have learned how to use Terraform functions that can help with each Terraform configuration you create for deploying AWS services, Azure, Oracle, and so on.

With this newfound knowledge, why not encapsulate common parts of your code, and make them reusable by building Terraform modules? Or automate tasks invoking your functions with Terraform Docker integrations?