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

@jbardin has this changed again. I’m now hitting error when I use terraform import in Terraform v1.3.2.

Is there an alternative way to implement this correctly? In my case my_credentials var is a sensitive variable in the Terraform Cloud workspace what contains a json string of key=value secrets.

   37:   for_each     = jsondecode(nonsensitive(var.my_credentials))
│ 
│ The "for_each" map includes keys derived from resource attributes that cannot be determined until apply, and so Terraform cannot determine the full set of keys that will identify
│ the instances of this resource.
│ 
│ When working with unknown values in for_each, it's better to define the map keys statically in your configuration and place apply-time results only in the map values.
│ 
│ Alternatively, you could use the -target planning option to first apply only the resources that the for_each value depends on, and then apply a second time to fully converge.

This is a different situation, where values are unknown rather than sensitive.
This is also during import, which still has some limitations. I can’t say why var.my_credentials might be unknown during import, can you provide a complete example?

@jbardin - I have a workaround. Cause is this bug `remote` backend does not allow imports with sensitive remote variables · Issue #26494 · hashicorp/terraform · GitHub
Because it’s sensitive I have to set it locally so terraform import works