Concatenate two lists in Terraform 0.12 - concat()

2 min read 06-10-2024
Concatenate two lists in Terraform 0.12 - concat()


Concatenating Lists in Terraform 0.12: A Simple Guide to the concat() Function

Terraform's concat() function is a powerful tool for combining lists in your infrastructure-as-code configurations. This article delves into how to effectively use concat() in Terraform 0.12, providing clear examples and explanations to enhance your understanding.

The Problem: Merging Lists for Complex Configurations

Imagine you're setting up a network with two separate lists: one for public subnets and another for private subnets. You need to combine these lists to define your complete subnet configuration. Manually writing out all the subnet details can be tedious and error-prone. This is where concat() comes in handy.

The Solution: concat() to the Rescue

Terraform's concat() function seamlessly merges two or more lists into a single combined list. Here's a simple example:

# Define your lists
locals {
  public_subnets = ["10.0.1.0/24", "10.0.2.0/24"]
  private_subnets = ["10.0.10.0/24", "10.0.11.0/24"]
}

# Concatenate the lists
locals {
  all_subnets = concat(local.public_subnets, local.private_subnets)
}

# Output the combined list
output "all_subnets" {
  value = local.all_subnets
}

This code defines two local variables, public_subnets and private_subnets, containing subnet CIDRs. The concat() function merges these lists, creating a new list all_subnets containing all the subnets. The output block then displays the contents of all_subnets.

Key Points to Remember

  • Order Matters: The order of the arguments passed to concat() determines the order of elements in the final list.
  • Flexibility: You can concatenate more than two lists by simply adding them as additional arguments to concat().
  • Data Types: All lists passed to concat() must contain elements of the same data type.

Beyond Simple Merging

concat() can be used in complex scenarios to build dynamic configurations based on various factors:

  • Conditional Merging: Combine lists based on specific conditions, such as resource availability or user input.
  • Dynamic List Generation: Construct a list of resources based on the size of another list or a variable.
  • Looping through Merged Lists: Iterate through the combined list to perform operations on all elements.

Conclusion

Mastering the concat() function in Terraform 0.12 is crucial for managing complex infrastructure configurations. It simplifies the process of combining lists, allowing you to create dynamic and efficient configurations. By understanding its basic usage and exploring its advanced applications, you can leverage its power to optimize your Terraform deployments.