0
0
TerraformHow-ToBeginner · 3 min read

How to Use Flatten Function in Terraform: Syntax and Examples

In Terraform, the flatten function takes a list of lists and merges them into a single list by removing one level of nesting. Use it when you have nested lists and want to simplify them into one list for easier processing.
📐

Syntax

The flatten function syntax is simple: it takes one argument, which must be a list of lists, and returns a single list with all the inner elements combined.

  • flatten(list_of_lists): The input is a list where each element is itself a list.
  • The output is a single list containing all elements from the inner lists in order.
terraform
flatten([["a", "b"], ["c", "d"], ["e"]])
Output
["a", "b", "c", "d", "e"]
💻

Example

This example shows how to use flatten to combine nested lists of strings into one list. It demonstrates how Terraform processes the nested structure.

terraform
variable "nested_list" {
  default = [["apple", "banana"], ["cherry", "date"], ["fig"]]
}

output "flat_list" {
  value = flatten(var.nested_list)
}
Output
flat_list = ["apple", "banana", "cherry", "date", "fig"]
⚠️

Common Pitfalls

Common mistakes when using flatten include:

  • Passing a list that is not nested (e.g., a flat list) will cause an error because flatten expects a list of lists.
  • Trying to flatten more than one level of nesting at once is not possible; flatten only removes one level.
  • Confusing flatten with concat, which joins lists but does not flatten nested lists.
terraform
/* Wrong: flatten on a flat list causes error */
# flatten(["a", "b", "c"])

/* Right: flatten on a list of lists */
flatten([["a"], ["b", "c"]])
📊

Quick Reference

flatten function summary:

  • flatten(list_of_lists) → single list
  • Removes one level of nesting
  • Input must be a list of lists
  • Use when you want to simplify nested lists

Key Takeaways

Use flatten to convert a list of lists into a single flat list by removing one nesting level.
The input to flatten must be a nested list; passing a flat list causes errors.
flatten only removes one level of nesting, not multiple levels.
Do not confuse flatten with concat; flatten merges nested lists, concat joins lists.
Use flatten to simplify complex list structures for easier Terraform processing.