Error: Missing map key: "The given key does not identify an element" in Terraform
Fixes Terraform's "Error: Missing map key" when indexing a map with a key that does not exist. Use when plan fails on var.map["key"] or local lookups. Switch to lookup() with a default or guard with try(); not for "Invalid index" (lists) or "Duplicate object key" (for expressions).
TL;DR
You indexed a map with a key it does not have (var.map["missing"]). Unlike some languages, Terraform errors instead of returning null. Use lookup(var.map, "missing", "default") to provide a fallback, or restructure so the key always exists.
The error
Error: Missing map key
on main.tf line 10, in output "secondary_location":
10: value = var.location["secondary"]
The given key does not identify an element in this collection value.Steps to fix
- Confirm the key is genuinely absent vs misspelled: print the map with
terraform consoleand evaluatevar.location.
- Expected: you see the actual key set.
- If the key is optional, use
lookupwith a default:
value = lookup(var.location, "secondary", "East US")- Expected: missing keys fall back to the default instead of erroring.
- If the key should always exist, fix the map (add the key to the variable default or the tfvars).
- Expected: the key set is complete.
- Re-run
terraform plan.
- Expected: plan proceeds.
When to use this
planfails withMissing map keyon bracket or dot access into a map, common with per-environment config maps and workspace-keyed locals.
When NOT to use this
Invalid indexis the list/tuple equivalent.Duplicate object keyis the for-expression collision. If the map itself is null, fix the null first.
Compatibility
- All Terraform versions;
lookupwith a default is available since 0.12.
Root cause
Map index operations in Terraform are strict: the key must exist. This is deliberate, catching typos and incomplete config at plan time rather than silently propagating nulls. lookup() is the explicit opt-out for keys that are legitimately optional.
Edge cases
lookupwithout a default still errors on missing keys; the default is what makes it safe.try(var.map["key"], "default")also works and handles null maps.- In
validationblocks, wrap the access incan()so a missing key fails validation gracefully instead of erroring.