Skip to main content

Command Palette

Search for a command to run...

Terraform Functions

Updated
5 min read


Make sure to:

Check the repo here: Click.

Here, the real tested codes are updated. This is updated with correctness. The blog below just consists of theory. I learned more by writing the code.


Terraform Functions

Unlike other programming languages, Terraform uses HCL. This HCL job is to provision the infrastructure. Thus, HCL doesn’t provide us with custom functions, as it is a configuration file; we can use the built-in functions.

These can be categorised into:

1. String Functions

These functions are used to manipulate strings, such as changing case, extracting substrings, or formatting.

FunctionDescriptionExampleOutput
lowerConverts the string to all lowercase letters.lower("AWS Instance")"aws instance"
upperConverts the string to all uppercase letters.upper("VPC Subnet")"VPC SUBNET"
substrExtracts a substring from a string.substr("terraform", 0, 4)"terr"
joinJoins a list of strings with a specified delimiter.join("-", ["app", "web", "01"])"app-web-01"
formatProduces a string by formatting a set of values (similar to C's sprintf).format("The ID is %04d", 12)"The ID is 0012"

2. Numeric Functions

These functions perform mathematical operations on numbers.

FunctionDescriptionExampleOutput
maxReturns the greatest of the given numbers.max(10, 20, 5)20
minReturns the least of the given numbers.min(10, 20, 5)5
ceilComputes the smallest whole number greater than or equal to the argument.ceil(3.14)4
floorComputes the largest whole number less than or equal to the argument.floor(3.9)3
absComputes the absolute value of the argument.abs(-15)15

3. Collection Functions

Collections refer to lists, maps, and sets. These functions manipulate and extract information from these data structures.

FunctionDescriptionExampleOutput
lengthReturns the number of elements in a list, map, or string.length(["a", "b", "c"])3
lookupRetrieves the value of a single element from a map, returning a default value if the key is not found.lookup({"a":"1", "b":"2"}, "c", "default")"default"
keysReturns a list containing the keys of a map.keys({"key1": 1, "key2": 2})["key1", "key2"]
valuesReturns a list containing the values of a map.values({"key1": 1, "key2": 2})[1, 2]
elementRetrieves a single element from a list or tuple.element(["a", "b", "c"], 1)"b"

4. Type Conversion Functions

These functions convert values from one data type to another.

FunctionDescriptionExampleOutput
tostringConverts the given value to a string.tostring(123)"123"
tonumberConverts the given value to a number.tonumber("42")42
toboolConverts the given value to a boolean.tobool("true")true
tolistConverts the given value to a list.tolist(set("a", "b"))["a", "b"]

5. File Function

The primary function here is used to read content from a local file. This is often used for supplying user data, scripts, or configuration files.

FunctionDescriptionExampleCommon Use Case
fileReads the content of the file at the given path.file("user_data.sh")Reading Shell Scripts for cloud instance User Data.
filebase64Reads the content and base64-encodes it.filebase64("config.yaml")Providing Base64-encoded input for cloud resources.

Example Usage in a .tf file:

Terraform

resource "aws_instance" "web" {
  # ... other configuration ...
  user_data = file("scripts/install_nginx.sh")
}

6. Validation Function (via precondition/postcondition)

Terraform uses precondition and postcondition blocks within resource and data blocks to define custom validation rules, using a dedicated error_message block to explain the failure. While not a standalone "validation function" in the same way, this is how you implement validation logic.

Example Code:

Terraform

resource "aws_s3_bucket" "example" {
  bucket = var.bucket_name
  # ...

  # Ensure the bucket name contains "prod" for production environment
  lifecycle {
    precondition {
      condition     = contains(lower(var.environment), "prod")
      error_message = "Production buckets must have 'prod' in the environment name."
    }
  }
}

7. Lookup Function

The lookup function is typically used within the Collection Functions category, as noted above, for safe retrieval of map values. It is one of the most common ways to manage environment-specific variables.

FunctionDescriptionExampleOutput
lookupRetrieves the value of a single element from a map, returning a default value if the key is not found.lookup({"dev": "t2.micro"}, "prod", "t3.medium")"t3.medium"

8. Date and Time Functions

These functions handle the manipulation and formatting of timestamps.

FunctionDescriptionExampleOutput
timestampReturns the current date and time in RFC 3339 format.timestamp()2025-12-05T09:06:30Z (Example)
formatdateFormats a date/time stamp using a custom format string.formatdate("YYYYMMDD", timestamp())20251205 (Example)

Example Usage in .tf files:

Check the repo here: Click.


Arigato!

More from this blog

Code Companions

32 posts