Terraform Mastery โ€“ Day 10: Functions in Terraform

Pritish AnandPritish Anand
3 min read

Introduction

Functions in Terraform enhance configurations by enabling dynamic values, data manipulation, and logical operations. They improve reusability, reduce redundancy, and help create more flexible infrastructure-as-code (IaC). Terraform provides built-in functions categorized into string, numeric, collection, encoding, filesystem, and date/time functions.

This guide explores essential Terraform functions, their usage, and examples to improve your IaC skills.


1. Types of Functions in Terraform

Terraform offers various built-in functions categorized as follows:

a) String Functions

String functions manipulate and transform text-based values.

๐Ÿ”น Common String Functions:

  • lower(string) โ†’ Converts text to lowercase.

  • upper(string) โ†’ Converts text to uppercase.

  • length(string) โ†’ Returns the length of a string.

  • replace(string, old, new) โ†’ Replaces occurrences of old with new.

  • trimspace(string) โ†’ Removes leading and trailing spaces.

Example:

variable "name" {
  default = "Terraform"
}

output "lowercase_name" {
  value = lower(var.name) // Output: terraform
}

b) Numeric Functions

Numeric functions help perform mathematical operations on numbers.

๐Ÿ”น Common Numeric Functions:

  • min(a, b, ...) โ†’ Returns the smallest number.

  • max(a, b, ...) โ†’ Returns the largest number.

  • abs(number) โ†’ Returns the absolute value of a number.

  • ceil(number) โ†’ Rounds up to the nearest integer.

  • floor(number) โ†’ Rounds down to the nearest integer.

Example:

output "min_value" {
  value = min(10, 5, 20) // Output: 5
}

c) Collection Functions

Collection functions work with lists, maps, and sets.

๐Ÿ”น Common Collection Functions:

  • length(collection) โ†’ Returns the number of elements.

  • contains(collection, value) โ†’ Checks if a value exists in a list.

  • join(separator, list) โ†’ Joins elements with a separator.

  • split(separator, string) โ†’ Splits a string into a list.

  • flatten(list_of_lists) โ†’ Flattens a nested list.

Example:

variable "my_list" {
  default = ["AWS", "Azure", "GCP"]
}

output "joined_clouds" {
  value = join(", ", var.my_list) // Output: AWS, Azure, GCP
}

d) Encoding Functions

These functions handle data conversions such as JSON encoding.

๐Ÿ”น Common Encoding Functions:

  • jsonencode(value) โ†’ Converts a Terraform value to JSON format.

  • jsondecode(json_string) โ†’ Converts JSON into a Terraform object.

  • base64encode(string) โ†’ Encodes a string in Base64.

  • base64decode(string) โ†’ Decodes a Base64-encoded string.

Example:

variable "my_map" {
  default = {
    name  = "Pritish"
    role  = "DevOps Engineer"
  }
}

output "json_output" {
  value = jsonencode(var.my_map)
}

Output:

{"name":"Pritish","role":"DevOps Engineer"}

e) Filesystem Functions

These functions handle file-based operations in Terraform.

๐Ÿ”น Common Filesystem Functions:

  • file(path) โ†’ Reads the content of a file.

  • templatefile(path, vars) โ†’ Loads a file and replaces placeholders with provided values.

Example:

output "read_file" {
  value = file("example.txt")
}

f) Date and Time Functions

Terraform provides date/time functions for timestamp manipulation.

๐Ÿ”น Common Date Functions:

  • timestamp() โ†’ Returns the current timestamp in UTC.

  • formatdate(format, timestamp) โ†’ Formats a timestamp.

  • timeadd(timestamp, duration) โ†’ Adds time to a timestamp.

Example:

output "current_time" {
  value = timestamp()
}

2. Combining Functions in Terraform

You can combine multiple functions to perform advanced operations.

Example: Using join(), upper(), and replace() together

variable "clouds" {
  default = ["aws", "azure", "gcp"]
}

output "modified_clouds" {
  value = replace(upper(join(", ", var.clouds)), "AWS", "Amazon Web Services")
}

Output:

Amazon Web Services, AZURE, GCP

3. Using Functions in Terraform Modules

Functions are commonly used in Terraform modules to enhance reusability.

Example: Using jsonencode() in a module

module "instance" {
  source = "./ec2_module"

  config = jsonencode({
    instance_type = "t3.micro"
    region        = "us-east-1"
  })
}

Conclusion

Terraform functions are essential for creating dynamic, scalable, and efficient infrastructure. They allow you to manipulate data, perform calculations, and optimize configurations effortlessly.

By mastering Terraform functions, you can enhance automation, improve code maintainability, and build powerful cloud environments. ๐Ÿš€

๐Ÿ”น Next Topic: Files in Terraform โ€“ Stay tuned for more!

0
Subscribe to my newsletter

Read articles from Pritish Anand directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Pritish Anand
Pritish Anand