DEV Community

Cover image for Day 11: Terraform Functions
Anil KUMAR
Anil KUMAR

Posted on

Day 11: Terraform Functions

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:

  1. String functions: manipulate and transform text
  2. Numeric functions: calculate max, min, absolute, etc.
  3. Collection functions: work with lists and maps
  4. Type conversion functions: convert between lists, sets, numbers, and strings
  5. Date and time functions: As the name indicates, works with timestamps and formatted dates
  6. 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"
Enter fullscreen mode Exit fullscreen mode
  • Lower Function: Converts the string to all lowercase letters.
> lower("TERRAFORM")
"terraform"
Enter fullscreen mode Exit fullscreen mode
  • Trim Function: trim(string, characters) removes unwanted characters (like spaces) from the beginning and end of a string.
trim(" terraform-challenge "," ")
"terraform-challenge"
Enter fullscreen mode Exit fullscreen mode
trim("anil","a")
"nil"
Enter fullscreen mode Exit fullscreen mode
  • Replace Function: replace(string, search, replace) replaces occurrences of a character or substring with another.
replace("anil kumar", " ", "-")
"anil-kumar"
Enter fullscreen mode Exit fullscreen mode
  • 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"
Enter fullscreen mode Exit fullscreen mode
  • 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"
Enter fullscreen mode Exit fullscreen mode

2. Numeric Functions in Terraform:

These functions perform mathematical operations on numbers like abs(), max(), min(), ceil(), floor(), sum().

max(5,7,9)
9
Enter fullscreen mode Exit fullscreen mode
min(5,9,7)
5
Enter fullscreen mode Exit fullscreen mode
abs(-56)
56
Enter fullscreen mode Exit fullscreen mode
ceil(3.4)
4
Enter fullscreen mode Exit fullscreen mode
floor(3.4)
3
Enter fullscreen mode Exit fullscreen mode
sum([2,3])
5
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
  • concat(): combines multiple lists into one.
concat([2,3,4],[5,6,7])
[
  2,
  3,
  4,
  5,
  6,
  7,
]
Enter fullscreen mode Exit fullscreen mode
  • merge(): combines multiple maps (key-value pairs).
merge({a=1},{b=2})
{
  "a" = 1
  "b" = 2
}
Enter fullscreen mode Exit fullscreen mode
  • reverse(): Reverses the list into exact opposite.
reverse([1,2,3])
[
  3,
  2,
  1,
]
Enter fullscreen mode Exit fullscreen mode
  • 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"
Enter fullscreen mode Exit fullscreen mode
tonumber("42")
42
Enter fullscreen mode Exit fullscreen mode
tobool("true")
true
Enter fullscreen mode Exit fullscreen mode
tolist(["a","b"])
tolist([
  "a",
  "b",
])
Enter fullscreen mode Exit fullscreen mode
> toset(["a","b","a"])
toset([
  "a",
  "b",
])
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode
formatdate("DD-MM-YYYY", timestamp())
"05-12-2025"
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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"
}
Enter fullscreen mode Exit fullscreen mode
terraform plan

Changes to Outputs:
  + name = "project-alpha-resource"

Enter fullscreen mode Exit fullscreen mode
  • 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"
  }
}
Enter fullscreen mode Exit fullscreen mode
terraform plan

Changes to Outputs:
  + name = {
      + company     = "HashiCorp"
      + cost_center = "abc-123"
      + environment = "Production"
      + managed_by  = "Terraform"
    }
Enter fullscreen mode Exit fullscreen mode

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!!!"
}
Enter fullscreen mode Exit fullscreen mode
terraform output
name = "projectalphastoragebucketwithcapsandspaces"
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode
terraform plan

Changes to Outputs:
  + name = "port-80-port-443-port-8080-port-3306"
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode
terraform plan

Changes to Outputs:
  + name = "t2.micro"
Enter fullscreen mode Exit fullscreen mode

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)