Today marks the Day 11 of 30 days of Terraform challenge by Piyush Sachdev. Today we will dive deep into the Terraform Functions.
Functions:
First of all, what is a function. Function is something that makes your life easy by making use of the code block repeatedly in the file without writing that multiple times. In Terraform you cannot create any custom challenges like as you do in other programming languages with syntax.
Instead, Terraform provides a set of inbuilt functions that we can use anywhere in our configurations. These helpers cover a variety of tasks, including:
- String manipulation
- Numeric operations
- Collections (lists and maps)
- Type conversion
- Date and time handling
- Validation and lookup
Even though Terraform can’t do everything a programming language can, these inbuilt functions give us the power to write clean, reusable, and dynamic configurations for our infrastructure.
Types of Terraform Functions:
Here is the brief about what each built-in function will do:
- String functions: manipulate and transform text
- Numeric functions: calculate max, min, absolute, etc.
- Collection functions: work with lists and maps
- Type conversion functions: convert between lists, sets, numbers, and strings
- Date and time functions: As the name indicates, works with timestamps and formatted dates
- Validation and lookup function: check or select values dynamically
1. String functions:
These functions are used to manipulate strings, such as changing case, extracting substrings, or formatting.
- Upper Function: Converts the string to all uppercase letters.
> upper("terraform")
"TERRAFORM"
- Lower Function: Converts the string to all lowercase letters.
> lower("TERRAFORM")
"terraform"
- Trim Function: trim(string, characters) removes unwanted characters (like spaces) from the beginning and end of a string.
trim(" terraform-challenge "," ")
"terraform-challenge"
trim("anil","a")
"nil"
- Replace Function: replace(string, search, replace) replaces occurrences of a character or substring with another.
replace("anil kumar", " ", "-")
"anil-kumar"
- The first argument is the original string.
- The second is the character to replace.
The third is the new character.
Substring Function:
substr(string, start, length) extracts a portion of a string.
substr("anilkumar",0,5)
"anilk"
- Starts at index 0 (the first character) and goes up to length 3.
Perfect for trimming or formatting strings in Terraform.
Join Function:
Joins a list of strings with a specified delimiter.
join("-", ["aws", "with", "terraform"])
"aws-with-terraform"
2. Numeric Functions in Terraform:
These functions perform mathematical operations on numbers like abs(), max(), min(), ceil(), floor(), sum().
max(5,7,9)
9
min(5,9,7)
5
abs(-56)
56
ceil(3.4)
4
floor(3.4)
3
sum([2,3])
5
3. Collection Functions in Terraform:
Collections refer to lists, maps, and sets. These functions manipulate and extract information from these data structures such as length(), concat(), merge(), reverse(), toset(), tolist()
- length(): This function returns the number of elements in a list.
length([2,3,4,5])
4
- concat(): combines multiple lists into one.
concat([2,3,4],[5,6,7])
[
2,
3,
4,
5,
6,
7,
]
- merge(): combines multiple maps (key-value pairs).
merge({a=1},{b=2})
{
"a" = 1
"b" = 2
}
- reverse(): Reverses the list into exact opposite.
reverse([1,2,3])
[
3,
2,
1,
]
- toset() and tolist(): These functions converts the list into set and set into list.
5. Type Conversion
These functions convert values from one data type to another such as tonumber(), tostring(), tobool(), toset(), tolist()
As the above set name indicates these are used to convert the number to string, to convert string to number
tostring(123)
"123"
tonumber("42")
42
tobool("true")
true
tolist(["a","b"])
tolist([
"a",
"b",
])
> toset(["a","b","a"])
toset([
"a",
"b",
])
6. Date/Time Functions:
Terraform also allows us to work with timestamps or format dates such as timestamp(), formatdate()
timestamp(): returns the current time in a predefined format.
timestamp()
"2025-12-05T11:04:37Z"
formatdate("DD-MM-YYYY", timestamp())
"05-12-2025"
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.
Retrieves the value of a single element from a map, returning a default value if the key is not found.
lookup({"dev": "t2.micro"}, "t3.medium")
"t3.medium"
Assignments:
- Assignment 1: Project Naming
Using Lowercase and Replace:
locals {
formatted_project_name = lower(replace(var.project_name, " ", "-"))
}
output "name"{
value = local.formatted_project_name
}
variable "project_name" {
default = "Project ALPHA Resource"
}
terraform plan
Changes to Outputs:
+ name = "project-alpha-resource"
- Assignment 2: Resource Tagging:
Using merge function to merge tags
locals {
merged_tags = merge(var.default_tags, var.environment_tags)
}
output "name" {
value = local.merged_tags
}
variable "default_tags" {
default = {
company = "HashiCorp"
managed_by = "Terraform"
}
}
variable "environment_tags" {
default = {
environment = "Production"
cost_center = "abc-123"
}
}
terraform plan
Changes to Outputs:
+ name = {
+ company = "HashiCorp"
+ cost_center = "abc-123"
+ environment = "Production"
+ managed_by = "Terraform"
}
Assignment 3: S3 Bucket Naming
Using functions like substr(), replace(), lower()
locals {
formatted_bucket_name = replace(
replace(
lower(substr(var.bucket_name, 0, 63)),
" ", ""
),
"!", ""
)
}
output "name" {
value = local.formatted_bucket_name
}
variable "bucket_name" {
default = "ProjectAlphaStorageBucket with CAPS and spaces!!!"
}
terraform output
name = "projectalphastoragebucketwithcapsandspaces"
Assignment 4: Security Group Ports
Using split(), join(), for() functions to transform "80,443,8080" into security group rules
locals {
port_list = split(",", var.allowed_ports)
sg_rules = [for port in local.port_list : {
name = "port-${port}"
port = port
description = "Allow traffic on port ${port}"
}]
formatted_ports = join("-", [for port in local.port_list : "port-${port}"])
}
variable "allowed_ports" {
default = "80,443,8080,3306"
}
output "name" {
value = local.formatted_ports
}
terraform plan
Changes to Outputs:
+ name = "port-80-port-443-port-8080-port-3306"
Assignment 5: Environment Lookup
Using lookup() function to select instance size by environment
variable "instance_sizes" {
default = {
dev = "t2.micro"
staging = "t3.small"
prod = "t3.large"
}
}
locals {
instance_size = lookup(var.instance_sizes, var.environment, "t2.micro")
}
variable "environment" {
default= "dev"
}
output "name" {
value= local.instance_size
}
terraform plan
Changes to Outputs:
+ name = "t2.micro"
Conclusion:
This marks the end of Day 11 of our 30 days of terraform challenge. Today, we explored Terraform Functions: Part 1. We saw how these functions can make our Terraform configurations cleaner, smarter, and more dynamic.
See you later for Terraform Functions: Part 2 tomorrow.
Below is the Youtube Video for reference:

Top comments (0)