'Iterating over map to create key vault secrets throws error if secret doesn't exist

I have a map of key vault secrets that I would want to use in an application. Some of these already exist in Azure Key Vault:

variable "keyvault_secrets" {
  type = map(string)
  default = {
    service_bus = "AzureWebJobsServiceBus",
    mongo_connection = "MongoConnection",
    sendgrid_api_key = "SendgridApiKey",
    twilio_auth_token = "TwilioAccountAuthToken",
    twilio_sid = "TwilioAccountSid",
    twilio_message_service_sid = "TwilioMessageServiceSid",
    resdis_session_connection = "RedisSessionConnection"
  }
}

I then have the following blocks to create the key vault and secrets:

data "azurerm_key_vault_secret" "these" {
  for_each = var.keyvault_secrets
  key_vault_id = azurerm_key_vault.default.id
  name = each.value
}

resource "azurerm_key_vault_access_policy" "api" {
  key_vault_id = azurerm_key_vault.default.id
  object_id = azurerm_app_service.api[0].identity[0].principal_id
  tenant_id = data.azurerm_client_config.current.tenant_id
  depends_on = [azurerm_app_service.api]
  key_permissions = []
  secret_permissions = [
    "Get"
  ]
}

resource "azurerm_key_vault" "default" {
  location = var.azure_location
  name = "kv-quiztime-${terraform.workspace}-001"
  resource_group_name = azurerm_resource_group.default[0].name
  sku_name = module.vars.env["keyvault_plan_sku"]["name"]
  tenant_id = data.azurerm_client_config.current.tenant_id
  tags = local.common_tags
}

resource "azurerm_key_vault_secret" "these" {
  for_each = var.keyvault_secrets
  key_vault_id = azurerm_key_vault.default.id
  name = each.value
  value = data.azurerm_key_vault_secret.these[each.key] ? data.azurerm_key_vault_secret.these[each.key].value : "not set"
  content_type = "Connection String"
}

However, when I run terraform plan I get the following error:

Error: KeyVault Secret "RedisSessionConnection" (KeyVault URI "https://kv-[hidden]-dev-001.vault.azure.net/") does not exist │ │ with data.azurerm_key_vault_secret.these["resdis_session_connection"], │ on keyvaults.tf line 2, in data "azurerm_key_vault_secret" "these": │ 2: data "azurerm_key_vault_secret" "these" {

Because it doesn't exist, I would expect it to be created. What am I doing wrong? Or do I have incorrect expectations?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source