Error: Duplicate object key: "Two different items produced the key" in a for expression
Fixes Terraform's "Error: Duplicate object key ... Two different items produced the key" when a for expression emits the same map key twice. Use when plan fails building a map from concatenated lists. Make keys unique or add the grouping ellipsis (...); not for duplicate resource blocks.
TL;DR
Your { for ... : key [your value] value } produced the same key twice. Terraform refuses to guess which value wins. Either make the keys unique, or add the grouping ellipsis (...) after the value expression to collect duplicates into lists.
The error
Error: Duplicate object key
on .terraform/modules/repository/main.tf line 404, in locals:
398: teams = { for i in concat(
399: local.team_admin,
400: local.team_push,
401: local.team_pull,
402: local.team_triage,
403: local.team_maintain,
404: ) : i.slug => i }
Two different items produced the key "nios-build-write" in this 'for' expression.Steps to fix
Read which key collided (here:
nios-build-write). Find the two items that produce it.- Expected: you can point at both source items.
Decide: should duplicates merge or group? If one should win, restructure so keys are unique (e.g.
merge()several single-key maps, later arguments winning), or key by a composite like"${i.slug}-${i.permission}". If duplicates are legitimate, enable grouping:teams = { for i in local.all_teams : i.slug => i... }- Expected: each key maps to a list of values; downstream code indexes into lists.
Run
terraform validate, thenplanand check the resulting map.- Expected: no duplicate-key error; the map shape matches what consumers expect.
When to use this
plan/validatefails withDuplicate object keyin aforexpression building a map, usually after concatenating lists that can share keys.
When NOT to use this
Duplicate resource configurationis about resource blocks, not map keys. If the collision is unexpected, grouping with...hides a data bug; prefer making keys unique.
Compatibility
- Terraform 0.12+
forexpressions; the grouping ellipsis is available in all 1.x versions.
Root cause
Object construction requires unique keys. When two iterations emit the same key, Terraform cannot pick a value without silently dropping data, so it errors. The ... ellipsis opts into the explicit alternative: group values per key into a list.
Edge cases
for_eachover the resulting map with grouped values gives you lists per key; adjusteach.valuehandling.- The ellipsis only works when building objects, not tuples:
[for ... : k...]errors. distinct()on the input list before theforexpression is another way to force uniqueness when duplicates are noise.