Terraform: How to join list elements into a string

Updated: February 3, 2024 By: Guest Contributor Post a comment

Introduction

Terraform, an open-source infrastructure as code software tool developed by HashiCorp, is used to define and provision a datacenter infrastructure using a high-level configuration language known as HashiCorp Configuration Language (HCL), or optionally JSON. Terraform allows for the management of both cloud and on-premises resources with a single workflow. Understanding how to manipulate data structures such as lists and strings is crucial for optimizing your Terraform scripts. In this tutorial, you’ll learn how to join list elements into a string, enhancing your infrastructure as code practices. We’ll start from the basics and gradually move to more advanced techniques, including examples and their outputs.

Understanding Terraform Lists and Strings

A list in Terraform is a sequence of values that are of the same type. It’s one of the basic data structures that Terraform uses to store multiple values. A string, on the other hand, is a sequence of characters used to represent text. Occasionally, you may need to convert a list of values into a single string, possibly for display purposes, to set a single environment variable, or to pass data to a module or resource that expects a string input. The join() function in Terraform allows you to accomplish this task efficiently.

Basic Usage of the join() Function

The basic syntax for the join() function in Terraform is:

join("delimiter", list)

This function concatenates the elements of a given list into a single string, with each element separated by the specified delimiter. Let’s look at a simple example:

output "combined_string" {
  value = join(", ", ["apple", "banana", "cherry"])
}

In this example, the output would be:

"apple, banana, cherry"

This demonstrates the basic use of the join() function, producing a comma-separated string from a list of fruits.

Advanced Usage Scenarios

While the basic usage covers many scenarios, sometimes your requirements may be more complex. Let’s delve into some advanced techniques and use cases.

Joining Lists with Conditional Elements

There are situations where you may want to include elements in your string conditionally. Terraform’s compact() function, combined with list comprehensions, is quite useful here. For instance, consider you have a list with potential null values. You could use the following approach:

locals {
  fruits = ["apple", "", "banana", null, "cherry"]
}

output "non_empty_fruits" {
  value = join(", ", compact([for f in local.fruits : if f != "" && f != null then f else null]))
}

This script filters out empty strings and null values before joining the remaining items, resulting in:

"apple, banana, cherry"

Here, the compact() function removes any null values, and the list comprehension handles conditional inclusion based on the content of the item.

Joining Elements with Complex Conditions

For more complex scenarios, such as when elements to be included are based on multiple conditions, you may use nested list comprehensions or the flatten() function to simplify data structure manipulation. For example:

locals {
  items = [
    { name = "apple", include = true },
    { name = "banana", include = false },
    { name = "cherry", include = true }
  ]
}

output "included_items" {
  value = join(", ", [for item in local.items : if item.include then item.name else ""])
}

The output for this will be:

"apple, cherry"

This demonstrates filtering based on a condition within each element’s map.

Handling Lists of Maps

Lists of maps introduce an additional layer of complexity. Suppose you have a list of user objects, and you’d like to extract and concatenate a particular attribute (e.g., usernames) from each map. You can accomplish this by:

locals {
  users = [
    { name = "John", age = 30 },
    { name = "Doe", age = 25 }
  ]
}

output "usernames" {
  value = join(", ", [for user in local.users : user.name])
}

The output will list the names separated by commas:

"John, Doe"

This approach is straightforward for lists of maps when you need to extract and concatenate values of a specific key across all maps.

Using the join() Function with Other Terraform Functions

The join() function is often used in conjunction with other functions to perform complex data manipulation. Terraform provides a rich set of built-in functions that you can use to filter, map, and reduce your data before joining it into a string. Efficient use of these functions unlocks powerful data structuring and manipulation strategies, enhancing the manageability and readability of your Terraform configurations.

Conclusion

Mastering the join() function and its applications is a step toward more efficient and readable Terraform scripts. Whether you’re handling simple lists or complex lists of maps, understanding how to manipulate these data structures enables you to construct more dynamic and flexible infrastructure as code. The examples provided in this tutorial form a solid foundation for experimenting with and implementing your solutions.