Function merge()
📝 Description
The merge function takes an arbitrary number of maps and combines them into a single map. If a key exists in multiple maps, the value from the last map in the argument list wins (it overwrites the previous ones).
Use Case: Combining global tags (like
Owner,Environment) with resource-specific tags. This is the industry standard for tagging in AWS, Azure, and GCP.
💻 Syntax
💡 Examples
1. Basic Merging:
2. Overwriting Values (The "Last Wins" Rule):
If the same key appears twice, the rightmost map takes priority.
locals {
default_tags = {
Environment = "Dev"
ManagedBy = "Terraform"
}
extra_tags = {
Environment = "Prod" # This will overwrite "Dev"
Project = "Wiki"
}
}
# Result: { "Environment" = "Prod", "ManagedBy" = "Terraform", "Project" = "Wiki" }
output "final_tags" {
value = merge(local.default_tags, local.extra_tags)
}
3. Practical Scenario: Complex Tagging
resource "aws_instance" "web" {
# ... other config ...
tags = merge(
var.common_tags,
{
Name = "web-server-01"
Role = "frontend"
}
)
}
⚠️ Key Details
-
All arguments must be maps.
-
If you pass an empty map
{}, it simply gets ignored and doesn't affect the result. -
Order matters! Always put your "overrides" or more specific maps at the end of the function call.
🔗 Related Functions
-
[[lookup]] — Find a specific value in a map.
-
[[keys]] — List all keys from the resulting merged map.