Functions

Sign Up to Build

About this Architecture

Here is some information about this architecture.

How to Build This Solution

Here are the steps you can follow to build this solution on your own.

Terraform Functions are self-contained code modules that are built to perform a single task. Data is often taken in and processed, and a result is returned by functions. Like any other programming language, Terraform has many built-in functions for various purposes. You will see these functions throughout this course. It’s good to become familiar with them beforehand.

Note: Although there are many built-in functions, Terraform does not support user-defined functions.

Built-in Functions

Below are the main function types available in Terraform. We will use the terraform console command to practice these functions. Running this command provides an interactive command-line console for evaluating and experimenting with expressions and functions.

Setup a Working Directory & Files

We will create a working directory and some files to demonstrate some of the functions. Create a working directory on your computer.

$ mkdir functions-lab 
$ cd functions-lab
$ touch pwd.txt

Open pwd.txt and put in the following content:

thisisapassword

Start Terraform Console

Open up a command prompt and run terraform console. It will provide you an interactive console like shown below. You can provide functions and expressions and hit enter. It will show the output in the next line.

# start the console
$ terraform console
> 

Run through the rest of this lesson with the console.

Numeric Functions

Numeric functions deal with numbers inside the Terraform script. Developers can format numbers through different built-in functions.

# abs() - Returns the asoulte value of a number
> abs(8)
8
> abs(-16)
16

# min() - Selects the minimum value from a series of given numbers
> min(542, 34, 11)
11

# max() - Selects the minimum value from a series of given numbers
> max(542, 34, 11)
542

# log() - Returns the logarithm of a given number
> log(16,2)
4

String Functions

String functions are used often in TF scripts to format string values. There are many built-in functions like join(), format(), replace(), substr(), trim(), etc.

# join() - Concatenate values given in a list with the given delimeter
> join(",", ["sam", "tony", "alice"])
"sam,tony,alice"

# replace() - Replaces a string by searching the given substring value
> replace("12, 06, 2021", ",", "/")
"12/ 06/ 2021"

# substr() - Extracts a substring from the provided string
> substr("/usr/local/app", 1, -1) == "/"
false

# trim() - Trim unwanted characters in a given string
> trim("/c/:/mnt/users/documents/text:files", ":")
"/c/:/mnt/users/documents/text:files"

Collection Functions

These functions work with collections of values like concatenating a collection of strings, finding a value in each range, finds the length of a given value, etc.

# coalescelist() - takes any number of list arguments and returns the first one that isn't empty
> coalescelist([], ["c", "d"], ["a", "b"])
[
  "c",
  "d",
]  # --> returns the first list that is not empty

# contains() - Checks whether a given list contains the provided value
> contains(["alice", "bob", "coby"], "bob")
true

# element() - Retrieves a single element from a list
> element(["a", "b", "c"], 2)
"c" # --> takes the second from the list

# length() - Find the length of a given list, map, or string
> length(["10", "20","32", "55"])
4

# lookup() - Looks for a given value by the provided key
port = lookup(var.propeties[count.index], "port") # --> Looks for value with "port" key

# range() - Generates a list of numbers using a start value, a limit value, and a step value.
> range(1, 4)
tolist([
  1,
  2,
  3,
])

Encoding Functions

Encoding functions perform the encoding and decoding functionalities in a TF script. These functions come in handy when working with JSON files, zip files, secrets, etc.

# jsonencode() - Encodes a value into JSON format
> jsonencode({"conn_pass"="1234567890"})
"{
"conn_pass
":
"1234567890
"}"

# jsondecode() - Decodes the JSON string and get its value 
jsondecode("{
"conn_pass
":
"1234567890
"}")["conn_pass"]

Filesystem Functions

Filesystem functions are for file-related purposes.

# file() - Reads the contents of a file in a given path and return as a string
file("pwd.txt")

# templatefile() -  reads the file in a given path and renders content as a template
templatefile("pwd.txt",{})

Date and Time Functions

Like any other language, Date and time functions are the TF built-in functions to work with date and time scenarios.

# formatdate() - Converts a timestamp into a different time format
> formatdate("MMM DD, YYYY", "1997-01-11T23:11:00Z")
"Jan 11, 1997"

# timestamp() - Returns a UTC timestamp string in RFC 3339 format.
> timestamp()
"2021-09-15T18:26:42Z"

Hash and Crypto Functions

These functions perform hashing and encrypting in a TF script. Hashing functions are often used in AWS Lambda functions as lambda functions have a property that requires file-hash to check whether the script has been updated or not.

# filebase64sha256() - Hashes the contents of a given file
filebase64sha256("./pwd.txt")

# sha256() - Computes the SHA256 hash of a given string
> sha256("This is a secret")
"f2d9ad12c972f3f76c37268514de20f74d70603cd369f55f70b52472c1de1065"

IP Network Functions

These are used for networking purposes

# cidrhost() - Calculates a full host IP address within given IP address prefix
> cidrhost("10.12.127.0/20", 16)
"10.12.112.16"

# cidrsubnet() - Calculates a subnet addresses
> cidrsubnet("172.16.0.0/12", 4, 2)
"172.18.0.0/16"

Type Conversion Functions

Type conversion functions are used to convert the provided value into another type specified.

# sensitive() - Takes any value and turns into a sensitive value
sensitive(file("pwd.txt"))

# tomap() - Converts its argument to a map value
> tomap({"name" = "Tom", "age" = "25"})
tomap({
  "age" = "25"
  "name" = "Tom"
})

# tostring() - Converts its argument to a string value
> tostring(1)
"1"