Interview Prep/Terraform/Plan Errors and Unexpected Replacements

`Error: Invalid for_each argument` — `Sensitive values, or values derived from sensitive values, cannot be used as for_each arguments.`

IntermediateTroubleshootingPlan Errors and Unexpected Replacements
Answer

Likely causes → The map came from a sensitive = true variable or from a secret data source; even the keys become sensitive.

Diagnose → Trace the value back to a sensitive variable/output.

Fix → Iterate over non-secret keys only:

for_each = nonsensitive(toset(keys(var.db_users)))
# use var.db_users[each.key] inside for the secret values

Only use nonsensitive() when the keys are truly not secret.

Prevent → Split structures: a non-sensitive map of names/config and a separate sensitive map of secrets.

All Terraform questions

More on Plan Errors and Unexpected Replacements