Skip to main content

Command Palette

Search for a command to run...

Terraform Functions (Part 1): A Beginner-Friendly Deep Dive

Published
4 min read
Terraform Functions (Part 1): A Beginner-Friendly Deep Dive

Today was one of those days where Terraform finally started “clicking.” I spent my session exploring Terraform functions, and honestly, they’re much more powerful than I expected.

Functions in Terraform help us transform, validate, format, and manipulate data—without writing any extra scripts. They are simple, expressive, and extremely useful when working with dynamic infrastructure.

Here’s everything I learned today 👇


Terraform Functions — Categorized & Explained

Terraform has a huge library of functions, but today I focused only on the ones that matter the most when writing modules or reusable infra code.

Below are the categories I explored:


1️⃣ String Functions

These help with formatting, cleaning, and manipulating text.

🔹 lower() / upper()

Convert text to lowercase or uppercase.

🔹 replace()

Replace a part of a string.
Great for dynamically generating bucket names, resource names, etc.

🔹 substr()

Extract a piece of a string using index ranges.

🔹 trim()

Removes leading and trailing characters (default whitespace).

🔹 split()

Split a string into a list based on a delimiter.

🔹 join()

The opposite of split — join a list back into a string.

Examples

lower("RAJESH")              # "rajesh"
upper("rajesh")              # "RAJESH"
replace("hello world", " ", "-")  # "hello-world"
substr("rajesh", 0, 3)             # "raj"
trim("  rajesh ")                 # "rajesh"

2️⃣ Numeric Functions

These help handle numeric logic inside Terraform without external scripts.

🔹 abs()

Absolute value — removes the negative sign.

🔹 max() / min()

Return the highest or lowest number in a list

Examples

max(10, 122, 90)   # 124
min(1, 10, 8)   # 1
abs(-59)        # 59

3️⃣ Collection Functions

Collections = lists, maps, sets.
These functions help us transform or extract values.

🔹 length()

Count number of elements in a list/map/set.

🔹 concat()

Combine multiple lists into one.

🔹 merge()

Combine two or more maps.

🔹 reverse()

Reverse the order of a list.

🔹 toset() / tolist()

Convert one collection type into another.
This is helpful when modules expect a specific data type.

Examples

length([1, 2, 3])                 # 3
concat([1, 2], [3, 4])            # [1, 2, 3, 4]
merge({a=1}, {b=2})               # {a=1, b=2}

4️⃣ Type Conversion Functions

Terraform is strongly typed.
So, converting types is super important.

🔹 tonumber()

Convert string → number.

🔹 tostring()

Convert number/bool → string.

🔹 tobool()

Convert string → boolean (e.g., "true" → true).

🔹 toset()

Convert list → set (removes duplicates).

🔹 tolist()

Convert set → list (gives index-based access).

Examples

toset(["a", "b", "a"])   # toset(["a", "b"])
tonumber("46")           # 46

5️⃣ Lookup Functions

🔹 lookup()

Safely fetch a value from a map.
You can even set a default if the key doesn’t exist.

Perfect for optional configurations.


6️⃣ Date/Time Functions

These were surprisingly cool. Terraform can generate and format timestamps.

🔹 timestamp()

Gives current UTC timestamp.

Useful for tagging resources like:
created_at = timestamp()

🔹 formatdate()

Formats dates into custom formats like:
YYYY-MM-DD, RFC3339, etc.

Ideal for naming backups, logs, or versioning resources.

Realtime Examples In Terraform:

  • Using merge function

variable "default_tags" {
  description = "A map of default tags to apply to all resources"
  type        = map(string)
  default     = {
    comapany = "TechCorp"
    CostCenter = "IT001"
  }
}
variable "environment_tags" {
  description = "A map of environment-specific tags"
  type        = map(string)
  default     = {
    Environment = "Prod"
    Owner       = "Devops Team"
  }
}
locals{
  merged_tags = merge(var.default_tags, var.environment_tags)
}

 resource "aws_s3_bucket" "example" {
     bucket = "example-bucket-${local.project_name}"
     tags = local.merged_tags

 }
 output "ASG2" {
  value=aws_s3_bucket.example.tags
 }

  • Using substr, replace, lower functions

variable "bucket_name" {
  description = "The name of the S3 bucket"
  type        = string
  default     = "Project DAY11 Bucketname in terraform with hypen using function "  
}

locals {
    bucket_name_formatted = substr(replace(lower(var.bucket_name), " ", "-"), 0, 63)
}
 resource "aws_s3_bucket" "example" {
     bucket = local.bucket_name_formatted
     tags   = local.merged_tags
 }
output "ASG3" {
   value = aws_s3_bucket.example.bucket
 }
  • Using lookup() function

variable "instance_region" {
  default = {
    dev     = "us-east-1"
    staging = "us-east-2"
    prod    = "us-west-1"
  }
}
variable "environment" {
  default = "staging"
}
locals {
    instance_region = lookup(var.instance_region, var.environment, "us-east-1")
}
output "ASG5" {
  value = local.instance_region
}

#Output will be "us-east-2"

📺 Video That Helped Me Understand this concept:

Final Thoughts

Today’s biggest realization:
👉 Terraform functions help you write cleaner, smarter, and more reusable infrastructure code.

Instead of hardcoding things, functions let you make your configurations dynamic and intelligent.

This was only Part 1 — and I’ve barely scratched the surface.

If you found this helpful, stay tuned for Terraform Functions Part 2!

More from this blog

B

Build With Rajesh

31 posts