Sensitive values, or values derived from sensitive values cannot be used as for_each arguments

How do I workaround this error?

I pass in sensitive variables (from Terraform Cloud) and need to store then in Key Vault.
The variables in this case are a JSON string so I need to call jsondecode function to read them.

│ Error: Invalid for_each argument
│ 
│   on secrets.tf line 2, in resource "azurerm_key_vault_secret" "my_credentials":
│    2:   for_each     = jsondecode(var.my_credentials)
│     ├────────────────
│     │ var.my_credentials has a sensitive value
│ 
│ Sensitive values, or values derived from sensitive values, cannot be used
│ as for_each arguments. If used, the sensitive value could be exposed as a
│ resource instance key.
variable "my_credentials" {
  type        = string
  description = "My credentials in JSON format"
  sensitive = true
}

resource "azurerm_key_vault_secret" "my_credentials" {
  for_each         = jsondecode(var.my_credentials)
  name              = each.key
  value              = each.value
  key_vault_id  = module.keyvault.id
}

Hi @deasunk,

You can work around this using the nonsensitive function. (And the inverse sensitive function can be used to re-apply sensitivity to any needed values from the given map)

2 Likes