Terraform Functions
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.
| Function | Description | Example | Output |
lower | Converts the string to all lowercase letters. | lower("AWS Instance") | "aws instance" |
upper | Converts the string to all uppercase letters. | upper("VPC Subnet") | "VPC SUBNET" |
substr | Extracts a substring from a string. | substr("terraform", 0, 4) | "terr" |
join | Joins a list of strings with a specified delimiter. | join("-", ["app", "web", "01"]) | "app-web-01" |
format | Produces 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.
| Function | Description | Example | Output |
max | Returns the greatest of the given numbers. | max(10, 20, 5) | 20 |
min | Returns the least of the given numbers. | min(10, 20, 5) | 5 |
ceil | Computes the smallest whole number greater than or equal to the argument. | ceil(3.14) | 4 |
floor | Computes the largest whole number less than or equal to the argument. | floor(3.9) | 3 |
abs | Computes 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.
| Function | Description | Example | Output |
length | Returns the number of elements in a list, map, or string. | length(["a", "b", "c"]) | 3 |
lookup | Retrieves 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" |
keys | Returns a list containing the keys of a map. | keys({"key1": 1, "key2": 2}) | ["key1", "key2"] |
values | Returns a list containing the values of a map. | values({"key1": 1, "key2": 2}) | [1, 2] |
element | Retrieves 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.
| Function | Description | Example | Output |
tostring | Converts the given value to a string. | tostring(123) | "123" |
tonumber | Converts the given value to a number. | tonumber("42") | 42 |
tobool | Converts the given value to a boolean. | tobool("true") | true |
tolist | Converts 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.
| Function | Description | Example | Common Use Case |
file | Reads the content of the file at the given path. | file("user_data.sh") | Reading Shell Scripts for cloud instance User Data. |
filebase64 | Reads 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.
| Function | Description | Example | Output |
lookup | Retrieves 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.
| Function | Description | Example | Output |
timestamp | Returns the current date and time in RFC 3339 format. | timestamp() | 2025-12-05T09:06:30Z (Example) |
formatdate | Formats 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!