Function flatten()
📝 Description
The flatten function takes a list and replaces any elements that are lists with the individual elements of those inner lists. It "flattens" a multi-dimensional structure into a single-level list.
Use Case: Preparing data for a
for_eachloop. For example, if you have a list of VPCs and each has a list of Subnets,flattenhelps you get a single list of all subnets to create them in one go.
💻 Syntax
💡 Examples
1. Basic Flattening:
2. Deeply Nested Lists:
It works regardless of how many levels of nesting you have.
3. Practical Scenario: Network Subnets
Imagine you define your infrastructure like this:
variable "networks" {
default = [
{ id = "vpc-1", subnets = ["10.0.1.0", "10.0.2.0"] },
{ id = "vpc-2", subnets = ["10.1.1.0"] }
]
}
locals {
# We want a simple list of all subnets across all VPCs
all_subnets = flatten(var.networks[*].subnets)
# Result: ["10.0.1.0", "10.0.2.0", "10.1.1.0"]
}
⚠️ Key Details
-
flattenis recursive, meaning it will keep diving into lists until everything is at the top level. -
It only works on lists. If you have a map, you might need to use it with
values()orkeys()first. -
It is often used with the splat operator (
[*]) to extract nested attributes from a list of objects.
🔗 Related Functions
-
[[distinct]] — Often used after
flattento remove duplicate elements from the new list. -
[[values]] — To get lists of values from maps before flattening.