Skip to main content

Command Palette

Search for a command to run...

Day 11: Terraform Functions

Published
5 min read
Day 11: Terraform Functions

Terraform functions are built-in operations in HashiCorp Configuration Language (HCL) that provide logic and computation capabilities, allowing users to manage and transform data efficiently. While HCL is a configuration language, not a programming language, Terraform provides several utility functions to handle string manipulation, numeric operations, collections, type conversion, and date/time formatting.

Terraform Console: Testing Functions on the Fly

Before we dive into examples, it's worth mentioning the Terraform Console. This interactive REPL (Read-Eval-Print Loop) lets you test various Terraform functions and expressions without creating actual configuration files. To start the console, simply run:

terraform console

This can be extremely useful for quick experimentation and testing of function behavior.


Types of Terraform Functions

1. String Functions

Terraform provides a variety of string manipulation functions that help you format, replace, and extract parts of strings.

  • upper(): Converts a string to uppercase.

      upper("hello")  # Output: "HELLO"
    
  • lower(): Converts a string to lowercase.

      lower("HELLO")  # Output: "hello"
    
  • trim(): Removes leading and trailing spaces (or specified characters).

      trim(" hello ", " ")  # Output: "hello"
      trim(" hello ", "h")  # Output: " ello "
    
  • replace(): Replaces all occurrences of a substring within a string.

      replace("hello world", " ", "-")  # Output: "hello-world"
    
  • substr(): Extracts a substring based on a start index and length.

      substr("hello", 1, 2)  # Output: "el"
    

These string functions are essential for transforming data into the correct format, such as generating valid names or manipulating strings for API calls.

2. Numeric Functions

Numerical operations are common in Terraform configurations, especially when calculating sizes, limits, or thresholds. Here are some numeric functions available in Terraform:

  • max(): Returns the maximum value from a list of numbers.

      max(1, 2, 3)  # Output: 3
    
  • min(): Returns the minimum value from a list of numbers.

      min(1, 2, 3)  # Output: 1
    
  • abs(): Returns the absolute value of a number.

      abs(-1)  # Output: 1
    

These functions are useful when you're dealing with numeric properties in cloud resources (e.g., instance sizes or scaling limits).

3. Collection Functions

Terraform also includes functions for working with collections, like lists, sets, and maps.

  • length(): Returns the number of elements in a collection.

      length([1, 2, 3])  # Output: 3
    
  • concatenate(): Combines two collections into one.

      concatenate([1, 2, 3], [4, 5, 6])  # Output: [1, 2, 3, 4, 5, 6]
    
  • merge(): Merges two maps into one.

      merge({a = 1, b = 2}, {c = 3})  # Output: {a = 1, b = 2, c = 3}
    

Collection functions are extremely helpful when working with dynamic data, like combining multiple lists of values or iterating over key-value pairs in maps.

4. Type Conversion Functions

Sometimes you need to convert between different data types. Terraform provides functions for type conversions:

  • toset(): Converts a list to a set, removing duplicate values.

      toset([1, 2, 2, 3])  # Output: [1, 2, 3]
    
  • tonumber(): Converts a string to a number.

      tonumber("1")  # Output: 1
    

These type conversion functions are crucial when you're working with mixed data types and need to ensure that values are in the correct format for further processing or resource creation.

5. Date and Time Functions

Terraform allows you to handle date and time operations using the following functions:

  • timestamp(): Returns the current timestamp in ISO 8601 format.

      timestamp()  # Output: "2022-01-01T00:00:00Z"
    
  • formatdate(): Formats a date based on a specified format string.

      formatdate("DD-MM-YYYY", timestamp())  # Output: "01-01-2022"
    

These functions are often used in time-sensitive resources like logging, backup, or auto-scaling configurations, where the date and time need to be formatted in a particular way.


Example Use Cases

Example 1: Validating Bucket Name

You might need to format a bucket name to be compliant with AWS S3 naming rules, where spaces and special characters are not allowed. You can use Terraform's string functions to clean the input:

formatted_bucket_name = replace(
  replace(substr(tolower(var.bucket_name), 0, 63), " ", "-"),
  "!",
  ""
)

This example converts the bucket name to lowercase, trims spaces, and removes any exclamation marks (!), ensuring a valid and well-formed S3 bucket name.

Example 2: Port List for Security Groups

In situations where you need to create security group rules for multiple ports dynamically, you can split a comma-separated string into a list and iterate over it:

port_list = split(",", var.allowed_ports)

sg_rules = [for port in local.port_list : {
  name = "port-${port}"
  port = port
}]

This code splits a string into a list and generates security group rules for each port.

Example 3: Instance Sizes Based on Environment

Terraform's lookup() function is helpful when you need to define environment-specific resources. For example, selecting different EC2 instance sizes based on the environment:

instance_size = lookup(var.instance_sizes, var.environment, "t2.micro")

This ensures that each environment (e.g., dev, prod) gets the correct instance size, with a default value of t2.micro if the environment is unknown.


Video


Conclusion

Terraform's built-in functions provide a robust and efficient way to manipulate data within your configuration files. Whether you're dealing with string manipulation, numeric calculations, collections, or date formatting, these functions can help you write cleaner, more flexible Terraform code. By mastering these functions, you can reduce repetition, improve readability, and create configurations that are both dynamic and reusable.

More from this blog

Terraform lac with AWS challenge

27 posts