🐶
Terraform

Terraform: How to Concatenate Variables (With Examples)

By Filip on 11/12/2024

Learn how to effectively concatenate two variables in Terraform to simplify your infrastructure code and enhance its readability.

Terraform: How to Concatenate Variables (With Examples)

Table of Contents

Introduction

In Terraform, combining strings, a process known as concatenation, is essential for creating dynamic and flexible infrastructure configurations. This article explains the two primary methods for concatenating strings in Terraform: using the ${} syntax and the join() function. We'll illustrate when to use each approach and provide practical examples to guide you.

Step-by-Step Guide

To concatenate strings in Terraform, you can use the ${} syntax for simple cases or the join() function for more complex scenarios.

Using ${} for simple concatenation:

This approach is suitable for combining variables and literal strings directly within expressions.

variable "environment" {
  default = "prod"
}

resource "aws_instance" "example" {
  tags = {
    Name = "web-server-${var.environment}"
  }
}

In this example, the value of the Name tag will be "web-server-prod".

Using the join() function for more control:

The join() function is useful when you need to concatenate multiple strings with a specific delimiter.

variable "name_parts" {
  default = ["web", "server", "prod"]
}

output "full_name" {
  value = join("-", var.name_parts)
}

This code will output "web-server-prod", joining the elements of the name_parts list with hyphens.

Important Considerations:

  • For more complex string manipulations like splitting or replacing substrings, explore Terraform's built-in functions like split() and replace().
  • When working with lists of strings, the concat() function can be used to combine them into a single list.
  • Remember that Terraform performs string interpolation before executing functions, so be mindful of the order of operations in your code.

Code Example

This code repository provides examples of different string concatenation methods in Terraform. It showcases using ${} for simple variable and literal combinations, the join() function for concatenating lists with delimiters, and combining concat() and join() for more complex scenarios like creating domain lists with prefixes and suffixes. Each example includes code snippets and explanations of the output, demonstrating how to effectively manipulate strings in Terraform configurations.

This repository demonstrates different ways to concatenate strings in Terraform.

1. Simple Concatenation with ${}

This example shows how to combine a variable and a literal string to create a dynamic resource name.

main.tf:

variable "environment" {
  default = "prod"
}

resource "local_file" "example" {
  content = "This is an example file for ${var.environment} environment."
  filename = "output-${var.environment}.txt"
}

This code will create a file named "output-prod.txt" with the content "This is an example file for prod environment."

2. Concatenation with join() function

This example demonstrates using the join() function to concatenate a list of strings with a specific delimiter.

variables.tf:

variable "name_parts" {
  default = ["web", "server", "prod"]
}

main.tf:

output "full_name" {
  value = join("-", var.name_parts)
}

Running terraform apply will output:

Outputs:

full_name = web-server-prod

3. Combining concat() and join()

This example shows how to combine concat() and join() functions for more complex scenarios.

variables.tf:

variable "prefixes" {
  default = ["dev", "test"]
}

variable "suffix" {
  default = "example.com"
}

main.tf:

output "domains" {
  value = join(",", [for prefix in var.prefixes : "${prefix}.${var.suffix}"])
}

Running terraform apply will output:

Outputs:

domains = dev.example.com,test.example.com

This example first uses a for expression within the join() function to iterate over the prefixes list and create a list of strings like ["dev.example.com", "test.example.com"]. Then, it uses the join() function to concatenate these strings with a comma delimiter.

These examples demonstrate various ways to concatenate strings in Terraform. Remember to choose the method that best suits your needs and consider the order of operations when combining different functions.

Additional Notes

  • Readability: While ${} is concise for simple cases, using join() can improve readability when concatenating many strings or using a complex delimiter.
  • Flexibility: The join() function offers more flexibility by allowing you to specify any delimiter, while ${} directly embeds variables and literals.
  • Dynamic Delimiters: You can even use variables as delimiters within the join() function for highly dynamic scenarios.
  • Error Handling: Be mindful of potential errors when using ${} with variables that might be undefined. Using the coalesce() function can help provide default values and prevent errors.
  • Alternative to concat(): In many cases, using list comprehensions with join() can be a more readable and efficient alternative to concat() for combining lists of strings.
  • Terraform 0.12 and above: The introduction of first-class expressions in Terraform 0.12 simplified string concatenation, making the ${} syntax more powerful and intuitive.

By understanding these nuances and choosing the appropriate method for each situation, you can write cleaner, more maintainable, and robust Terraform code for your infrastructure deployments.

Summary

Method Description Example Result
${} Interpolation Simple concatenation of variables and literal strings within expressions. Name = "web-server-${var.environment} Name = "web-server-prod"
join() Function Concatenates multiple strings using a specified delimiter. join("-", ["web", "server", "prod"]) "web-server-prod"

Additional Tips:

  • Use built-in functions like split() and replace() for advanced string manipulation.
  • Utilize the concat() function to combine lists of strings.
  • Be aware of Terraform's string interpolation order (interpolation before function execution).

Conclusion

Mastering string concatenation in Terraform is crucial for building dynamic and adaptable infrastructure configurations. Whether you're assembling resource names, generating file paths, or crafting complex output strings, understanding when to leverage the ${} syntax for simple embedding or the join() function for controlled concatenation with delimiters is key. Remember to utilize Terraform's built-in functions for advanced string operations and consider readability and error handling in your code. By effectively wielding these techniques, you can write cleaner, more efficient, and robust Terraform code that empowers you to manage your infrastructure with precision and flexibility.

References

Were You Able to Follow the Instructions?

😍Love it!
😊Yes
😐Meh-gical
😞No
🤮Clickbait