Skip to content

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_each loop. For example, if you have a list of VPCs and each has a list of Subnets, flatten helps you get a single list of all subnets to create them in one go.


💻 Syntax

flatten(list)

💡 Examples

1. Basic Flattening:

# Result: [1, 2, 3, 4]
output "flat_list" {
  value = flatten([[1, 2], [3, 4]])
}

2. Deeply Nested Lists:

It works regardless of how many levels of nesting you have.

# Result: ["a", "b", "c", "d"]
output "deep_flat" {
  value = flatten([["a", ["b", "c"]], "d"])
}

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

  • flatten is 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() or keys() first.

  • It is often used with the splat operator ([*]) to extract nested attributes from a list of objects.


  • [[distinct]] — Often used after flatten to remove duplicate elements from the new list.

  • [[values]] — To get lists of values from maps before flattening.

  • Official HashiCorp Docs