0
0
Terraformcloud~5 mins

Collection functions (length, flatten, merge) in Terraform - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes you have lists or maps in your infrastructure code and you need to count items, combine lists, or join maps. Terraform collection functions help you do this easily and correctly.
When you want to count how many servers or resources are in a list.
When you have nested lists and want to make them one simple list.
When you want to combine two or more maps into one map.
When you need to process data from multiple sources into a single collection.
When you want to simplify complex data structures for easier use in your configuration.
Config File - main.tf
main.tf
variable "list_of_lists" {
  type = list(list(string))
  default = [["app1", "app2"], ["app3", "app4"]]
}

variable "map1" {
  type = map(string)
  default = {
    region = "us-east-1"
    env    = "prod"
  }
}

variable "map2" {
  type = map(string)
  default = {
    owner = "team-a"
    env   = "staging"
  }
}

output "length_of_first_list" {
  value = length(var.list_of_lists[0])
}

output "flattened_list" {
  value = flatten(var.list_of_lists)
}

output "merged_maps" {
  value = merge(var.map1, var.map2)
}

This Terraform file defines two variables: a list of lists of strings and two maps of strings. It then outputs:

  • length_of_first_list: counts how many items are in the first list inside the list of lists.
  • flattened_list: combines all inner lists into one simple list.
  • merged_maps: combines two maps into one, with later keys overriding earlier ones if duplicated.
Commands
Initializes the Terraform working directory, downloads providers, and prepares for running plans or applies.
Terminal
terraform init
Expected OutputExpected
Initializing the backend... Initializing provider plugins... - Finding latest version of hashicorp/random... - Installing hashicorp/random v3.4.3... - Installed hashicorp/random v3.4.3 (signed by HashiCorp) Terraform has been successfully initialized! You may now begin working with Terraform. Try running "terraform plan" to see any changes that are required for your infrastructure. If you ever set or change modules or backend configuration for Terraform, rerun this command to reinitialize your working directory. If you forget, other commands will detect it and remind you to do so if necessary.
Applies the Terraform configuration to show the output values of the collection functions without manual approval.
Terminal
terraform apply -auto-approve
Expected OutputExpected
Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols: # output.length_of_first_list will be created # output.flattened_list will be created # output.merged_maps will be created Plan: 0 to add, 0 to change, 0 to destroy. Changes to Outputs: + length_of_first_list = 2 + flattened_list = ["app1", "app2", "app3", "app4"] + merged_maps = { "env" = "staging" "owner" = "team-a" "region" = "us-east-1" } Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
-auto-approve - Automatically approves the apply step without prompting
Key Concept

If you remember nothing else from this pattern, remember: length counts items, flatten merges nested lists into one, and merge combines maps with later keys overriding earlier ones.

Common Mistakes
Using merge on lists instead of maps
merge only works on maps; using it on lists causes errors.
Use flatten to combine nested lists and merge only for maps.
Trying to flatten a non-list or a flat list
flatten expects a list of lists; giving it a flat list returns it unchanged but may confuse users.
Only use flatten when you have nested lists to combine.
Expecting merge to keep all duplicate keys
merge overwrites duplicate keys with the last map's value, so some data may be lost.
Be aware of key conflicts and order maps accordingly.
Summary
Use length() to count how many items are in a list.
Use flatten() to combine nested lists into one simple list.
Use merge() to combine multiple maps into one, with later keys overriding earlier ones.