0
0
TerraformHow-ToBeginner · 3 min read

How to Use the Merge Function in Terraform

In Terraform, the merge function combines two or more maps into a single map. It returns a new map containing all keys and values, where later maps override earlier ones if keys repeat. Use it to easily join multiple sets of key-value pairs.
📐

Syntax

The merge function takes two or more maps as arguments and returns a single map. If keys overlap, the value from the last map wins.

  • merge(map1, map2, ...): Combines all maps into one.
  • Maps are key-value pairs enclosed in {}.
  • Later maps override earlier maps on key conflicts.
terraform
merge(map1, map2, ...)
💻

Example

This example shows how to merge two maps of server tags. The second map overrides the Environment key from the first.

terraform
variable "tags1" {
  default = {
    Environment = "dev"
    Owner       = "team-a"
  }
}

variable "tags2" {
  default = {
    Environment = "prod"
    Project     = "website"
  }
}

output "merged_tags" {
  value = merge(var.tags1, var.tags2)
}
Output
{ Environment = "prod" Owner = "team-a" Project = "website" }
⚠️

Common Pitfalls

Common mistakes include:

  • Passing non-map types causes errors.
  • Expecting deep merge: merge only merges top-level keys, not nested maps.
  • Overlapping keys get overwritten silently, which can cause unexpected results.

Always check your maps and key names carefully.

terraform
/* Wrong: merging a map and a list causes error */
merge({a = 1}, [1, 2])

/* Right: merge only maps */
merge({a = 1}, {b = 2})
📊

Quick Reference

Tips for using merge:

  • Use to combine multiple maps into one.
  • Later maps override earlier ones on duplicate keys.
  • Only merges top-level keys, not nested maps.
  • All arguments must be maps.

Key Takeaways

Use merge to combine two or more maps into a single map in Terraform.
Later maps override earlier maps when keys overlap in merge.
All arguments to merge must be maps; mixing types causes errors.
merge only merges top-level keys, not nested maps.
Check your keys carefully to avoid silent overwrites.