Bird
Raised Fist0
Terraformcloud~5 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. What does the Terraform function length() do when applied to a list?
easy
A. Returns the number of items in the list
B. Combines all items into a single string
C. Flattens nested lists into one list
D. Merges the list with another list

Solution

  1. Step 1: Understand the purpose of length()

    The length() function counts how many elements are in a list, map, or string.
  2. Step 2: Apply to a list context

    When used on a list, it returns the total number of items inside that list.
  3. Final Answer:

    Returns the number of items in the list -> Option A
  4. Quick Check:

    length(list) = count of items [OK]
Hint: Count items with length() to get list size fast [OK]
Common Mistakes:
  • Thinking length() merges lists
  • Confusing length() with flatten()
  • Assuming length() returns the list itself
2. Which of the following is the correct syntax to merge two maps map1 and map2 in Terraform?
easy
A. length(map1, map2)
B. flatten(map1, map2)
C. map1 + map2
D. merge(map1, map2)

Solution

  1. Step 1: Identify the function for combining maps

    The merge() function is used to combine two or more maps into one.
  2. Step 2: Check syntax correctness

    The correct syntax is merge(map1, map2). Other options either use wrong functions or invalid operators.
  3. Final Answer:

    merge(map1, map2) -> Option D
  4. Quick Check:

    merge() combines maps correctly [OK]
Hint: Use merge() with parentheses and commas for maps [OK]
Common Mistakes:
  • Using + operator to merge maps
  • Confusing flatten() with merge()
  • Passing maps without commas
3. What is the output of this Terraform expression?
flatten([["a", "b"], ["c"], ["d", "e"]])
medium
A. [["a", "b"], ["c"], ["d", "e"]]
B. ["a", "b", "c", "d", "e"]
C. ["a", "b", ["c"], "d", "e"]
D. Error: flatten() only works on maps

Solution

  1. Step 1: Understand flatten() function

    The flatten() function takes a list of lists and combines all inner lists into one single list.
  2. Step 2: Apply flatten() to the given nested list

    Input is [["a", "b"], ["c"], ["d", "e"]]. Flattening merges all inner lists into ["a", "b", "c", "d", "e"].
  3. Final Answer:

    ["a", "b", "c", "d", "e"] -> Option B
  4. Quick Check:

    flatten(nested list) = single list [OK]
Hint: flatten() removes inner list brackets to one list [OK]
Common Mistakes:
  • Thinking flatten() returns original nested list
  • Expecting flatten() to work on maps
  • Confusing flatten() with merge()
4. Given the code snippet:
locals {
  map1 = { a = 1, b = 2 }
  map2 = { b = 3, c = 4 }
  result = merge(map1, map2)
}

What is the value of local.result?
medium
A. { a = 1, b = 3, c = 4 }
B. { a = 1, b = 2, c = 4 }
C. { a = 1, b = 5, c = 4 }
D. Error: duplicate keys not allowed in merge

Solution

  1. Step 1: Understand merge() behavior with duplicate keys

    When keys overlap, the value from the last map argument overrides earlier ones.
  2. Step 2: Apply merge to map1 and map2

    map1 has b=2, map2 has b=3. The merged map uses b=3 from map2, so result is { a=1, b=3, c=4 }.
  3. Final Answer:

    { a = 1, b = 3, c = 4 } -> Option A
  4. Quick Check:

    merge() overrides duplicate keys with last map [OK]
Hint: Last map's keys override earlier ones in merge() [OK]
Common Mistakes:
  • Assuming values add up for duplicate keys
  • Expecting error on duplicate keys
  • Confusing merge() with flatten()
5. You have a list of maps:
list_of_maps = [
  { name = "Alice", age = 30 },
  { name = "Bob", age = 25 },
  { name = "Carol", age = 27 }
]

Which Terraform expression correctly merges all maps into one map with all keys and values combined?
hard
A. length(list_of_maps)
B. flatten(list_of_maps)
C. merge(list_of_maps...)
D. merge(list_of_maps)

Solution

  1. Step 1: Understand how to merge multiple maps in a list

    To merge all maps inside a list, you use the splat operator ... to unpack the list as arguments to merge().
  2. Step 2: Check each option

    merge(list_of_maps...) uses merge(list_of_maps...) which correctly merges all maps. flatten(list_of_maps) tries flatten on maps (invalid), C returns count, D passes list directly (invalid).
  3. Final Answer:

    merge(list_of_maps...) -> Option C
  4. Quick Check:

    Use merge() with ... to combine list of maps [OK]
Hint: Use ... to unpack list when merging maps [OK]
Common Mistakes:
  • Passing list directly to merge() without ...
  • Using flatten() on maps
  • Confusing length() with merge()
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard