Skip to main content

Command Palette

Search for a command to run...

DAY #36: [DAY-11] AWS Terraform Functions (Part-1)

Let’s Learn How Built-In Terraform Functions Make Configuration Flexible and Error-Free

Updated
9 min read
DAY #36: [DAY-11] AWS Terraform Functions (Part-1)
A
Sharing real-time progress, roadblocks, and open source lessons. Hoping my notes help someone else feel less stuck. "Stop waiting to feel ready, stop waiting for the perfect moment, start messy, start scared and start before you feel qualified"

Introduction

Hello and welcome back to our 30 Days of AWS Terraform journey! How’s everyone doing today? I hope life is treating you kindly and that you’re finding a little time to enjoy this learning adventure with me.

Last session, we dived into some fascinating pieces of Terraform i.e. conditional expressions, splat expressions, and dynamic blocks. Each of these little gems helped us see how Terraform makes infrastructure descriptions more flexible and expressive.

🚀 Crash Course: Terraform Basics for Freshers - DEV Community

Today, we’re turning our attention to Terraform Functions: Part 1.

Now, if the word “function” makes you imagine complicated programming, don’t worry, that’s not what we’re doing here. Terraform isn’t a programming language. It’s a configuration language, which simply means we describe what we want our infrastructure to look like, rather than writing a program to compute it. And to make that description a bit smarter and more reusable, Terraform provides built-in helpers called functions.

Because there are so many functions, we’ll explore them in two parts. In Part 1, we’ll cover what a function really is, why Terraform only gives us inbuilt functions, and how these helpers can make our variables and values cleaner and easier to manage.

This journey isn’t about overwhelming us it’s about learning small, practical tools that help us express what we already know in a smarter, more organized way.

And here’s a little personal tidbit:

Fact #11: I prefer learning from YouTube tutorials instead of going through documentation. For me, I like to see things in action, that makes things click faster for me.

Understanding Functions and Terraform’s Inbuilt Functions

What is a Function, Really?

Before we dive into Terraform-specific functions, let’s take a moment to understand what a function really is, in the simplest way possible.

In plain language, a function is something that makes our life easier. How? By letting us reuse instructions instead of writing the same steps over and over again.

Imagine this: we want to add two numbers. In a typical programming language, we might write something like this:

Simple enough. But what if we had to do this 10 different times, with different numbers each time? Sure, we could copy and paste those four lines again and again, but that’s inefficient and tedious.

This is exactly where a function comes in. Instead of rewriting the same code multiple times, we wrap it once in a function, and then just call it whenever we need it, passing in the numbers we want to add. The logic is reused, our code stays clean, and our work becomes faster and more organized.

Terraform is Not a Programming Language

Now, we might already know this, but it’s worth repeating: Terraform isn’t a full-fledged programming language. It’s a configuration language, officially called HCL i.e. HashiCorp Configuration Language.

terraform Memes & GIFs - Imgflip

What does that mean?

  • Terraform does not have classes, objects, or traditional OOP features.

  • We cannot create our own custom functions.

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.

Categories of Terraform Functions

Here’s a bird’s-eye view of the function categories we’ll explore:

  • 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:work with timestamps and formatted dates

  • Validation and lookup function: check or select values dynamically

Terraform String Functions

Now that we understand what a function is and why Terraform provides inbuilt functions, let’s explore string functions, these are some of the most commonly used helpers in Terraform.

String functions let us manipulate text, making it easier to format, clean, or transform strings before using them in our infrastructure.

1. Upper and Lower Functions

  • upper() converts a string to uppercase.

  • lower() converts a string to lowercase.

Example:

Notice how we call the function and pass the string as an argument. This is exactly how functions let us reuse logic without rewriting it.

2. Trim Function

  • trim(string, characters) removes unwanted characters (like spaces) from the beginning and end of a string.

Examples:

  • The first argument is the string to clean.

  • The second argument is the character to remove.

3. Replace Function

  • replace(string, search, replace) replaces occurrences of a character or substring with another.

Example:

  • The first argument is the original string.

  • The second is the character to replace.

  • The third is the new character.

4. Substring Function

  • substr(string, start, length) extracts a portion of a string.

Example:

  • Starts at index 0 (the first character) and goes up to length 3.

  • Perfect for trimming or formatting strings in Terraform.

These functions are especially helpful when we need to clean inputs, format names, or prepare strings for resources like S3 bucket names, which have strict naming rules.

Numeric and Collection Functions in Terraform

1. Numeric Functions

Numeric functions help perform simple calculations or analyze numbers.

max(): returns the largest number in a set.

  • min(): returns the smallest number.

  • abs(): returns the absolute value (removes the negative sign).

These functions are helpful when working with variables where you might need to select limits, bounds, or ensure positive values.

2. Collection Functions

Collection functions let us manipulate lists and maps, which are fundamental in Terraform for storing multiple values.

  • length(): returns the number of elements in a list.

  • concat(): combines multiple lists into one.

  • merge(): combines multiple maps (key-value pairs).

Collections are very common in Terraform. For example, when managing tags, security group rules, or multiple ports, these functions let us combine, iterate, and manipulate values cleanly and dynamically.

Type Conversion and Date/Time Functions in Terraform

In Terraform, sometimes we need to change the type of a value or work with time-based data. This is where type conversion and date/time functions come in handy.

1. Type Conversion Functions

Type conversion functions let us change one type of value into another, ensuring Terraform can handle it correctly.

  • toset(): converts a list into a set.

  • tonumber(): converts a string representing a number into an actual numeric value.

Note: In Terraform, anything in double quotes is treated as a string, even if it looks like a number. So we use tonumber() to ensure numeric operations work correctly.

2. Date and Time Functions

Terraform also allows us to work with timestamps or format dates:

  • timestamp(): returns the current time in a predefined format.

  • formatdate(): allows custom formatting of the timestamp.

These functions are useful when we need timestamps for logs, resources, or versioning, or when a specific format is required for our infrastructure configurations.

Using Terraform Functions in Practical AWS Examples

Let’s see how some of the Terraform functions we discussed can be applied in real configurations.

1. Lowercase and Replace for Variable Formatting

Imagine we have a variable for our project name:

We can use the lower() function to convert it to lowercase:

  • Output will be: "mission is terraform"

Now, if we want to replace spaces with hyphens, we can combine functions:

  • Output: "mission-is-terraform"

This ensures names are clean, lowercase, and safe for resources like S3 buckets.

2. Merge Function for Tags

Terraform often uses maps for tags. We might have default tags and environment-specific tags:

  • merge() combines the two maps into one, ensuring all tags are applied without duplication.

  • This is a practical way to manage resource metadata consistently.

3. Substring, Lower, Replace for Bucket Names

S3 bucket names have restrictions: no capitals, no spaces, max 64 characters.

We can enforce this using multiple functions together:

  • lower() → converts to lowercase

  • substr() → limits length to 64 characters

  • replace() → replaces spaces with hyphens

Even if someone provides a bucket name with capitals or spaces, Terraform automatically formats it safely, preventing errors during terraform apply.

4. Split and For Expression for Multiple Ports

Suppose we have a variable with comma-separated ports:

  • First, split the string into a list:

  • Then, iterate over the list to create structured data:

This is a simple way to convert a string input into multiple security group rules, automating repetitive work.

5. Lookup Function for Environment-Specific Values

Sometimes, we want Terraform to pick a value automatically based on the environment we’re working in. For example, maybe we want smaller instances for development and larger instances for production.

Here’s a simple example:

Let’s break this down:

  1. var.instance_sizes → This is a map that tells Terraform which instance to use for each environment.

    • dev → t2.micro

    • staging → t3.small

    • prod → t3.large

  2. var.environment → This tells Terraform which environment we are currently working in. Here, the default is "dev".

  3. lookup() → This function looks at the map, finds the key that matches the environment, and returns the corresponding value.

    • First argument: the map of values (var.instance_sizes)

    • Second argument: the key to look up (var.environment)

    • Third argument: the default value to use if the key is missing ("t2.micro")

So in this example:

  • Terraform sees that the environment is dev.

  • It looks in the map and finds dev = t2.micro.

  • It sets local.instance_size to "t2.micro".

This approach makes your configuration flexible and safe, because you can switch environments without manually changing values everywhere.

Conclusion

And just like that, we’ve reached the end of Day 11 of our 30 Days of AWS Terraform journey.

Today, we explored Terraform Functions: Part 1. We saw how these functions can make our Terraform configurations cleaner, smarter, and more dynamic.

I know, at first glance, some of these functions might seem a little tricky. We might even wonder, “Do I really need all these extra steps?” Believe me, I’ve felt the same way.

But here’s the thing: if these functions exist, it’s because they are designed to make our lives easier. Instead of rewriting the same logic over and over, they help us reuse, automate, and avoid mistakes, so we can spend our energy on what truly matters i.e. building great infrastructure.

So, with that thought in mind, I’ll leave you here for today. Take a little time to practice what we covered, play around with the examples, and let the concepts sink in.

If any doubts remain, here’s a video by Piyush Sachdeva that explains these concepts in another friendly way, which might help clear up any lingering questions.

Tomorrow, we’ll continue with Terraform Functions Part 2, diving into more functions and practical examples to make your configurations even more powerful.

Until then, take care, stay curious, and peace out!