0
0
TerraformHow-ToBeginner · 3 min read

How to Use concat Function in Terraform: Syntax and Examples

In Terraform, the concat function joins two or more lists into a single list by combining their elements in order. Use concat(list1, list2, ...) to merge lists, which is helpful for building combined resource attributes.
📐

Syntax

The concat function takes two or more lists as arguments and returns a new list containing all elements from each input list in order.

  • list1, list2, ...: Lists to join together.
  • Returns: A single list with all elements combined.
terraform
concat(list1, list2, ...)
💻

Example

This example shows how to join two lists of strings into one list using concat. It outputs the combined list.

terraform
variable "list_a" {
  type    = list(string)
  default = ["apple", "banana"]
}

variable "list_b" {
  type    = list(string)
  default = ["cherry", "date"]
}

output "combined_list" {
  value = concat(var.list_a, var.list_b)
}
Output
["apple", "banana", "cherry", "date"]
⚠️

Common Pitfalls

Common mistakes when using concat include:

  • Passing non-list arguments causes errors because concat only works with lists.
  • Trying to concatenate strings directly instead of lists of strings.
  • Using concat with empty lists is valid but returns just the combined lists.

Always ensure inputs are lists to avoid errors.

terraform
/* Wrong: passing strings instead of lists */
output "wrong_concat" {
  value = concat("apple", "banana")
}

/* Right: passing lists */
output "right_concat" {
  value = concat(["apple"], ["banana"])
}
📊

Quick Reference

concat function summary:

  • concat(list1, list2, ...): Joins multiple lists into one.
  • Input: Two or more lists.
  • Output: Single combined list.
  • Use for combining resource attributes or variables.

Key Takeaways

Use concat to join two or more lists into a single list in Terraform.
All arguments to concat must be lists; passing strings directly causes errors.
concat preserves the order of elements from each list in the result.
It is useful for combining multiple resource attributes or variable lists.
Empty lists can be safely concatenated without errors.