Avoid creating new azure key vault secret version if one already exists via terraform

Viewed 1250

The terraform code creates an azure key vault secret successfully during the first apply, but with consecutive applies, it still is trying to update the secret because of the changes in the expiration time.

resource "azurerm_key_vault_secret" "supportedTen" {
  name         = "supportedTen"
  value        = var.supportedTen
  key_vault_id = azurerm_key_vault.vault.id
  expiration_date = timeadd(timestamp(), "2160h")
  depends_on = [azurerm_key_vault_access_policy.vault]
}

2nd terraform apply onwards-

  # azurerm_key_vault_secret.supportedTenants will be updated in-place
  ~ resource "azurerm_key_vault_secret" "supportedTen" {
      ~ expiration_date = "2021-10-10T19:45:05Z" -> (known after apply)
        id              = "https://uri/secrets/supportedTen/abcde-secret-version"
        key_vault_id    = "/subscriptions/subscriptionid/resourceGroups/resourcegroup--id/providers/Microsoft.KeyVault/vaults/test-kv-dev"
        name            = "supportedTenants"
        tags            = {}
        value           = (sensitive value)
        version         = "abcde-secret-version"
    }

Is there any way I can put a condition if the expiration time is not expired or the secret version value is not empty(""), don't update the azure key vault secret resource?

2 Answers

you can use the lifecycle meta-argument to ignore expiration date.

resource "azurerm_key_vault_secret" "supportedTen" {
  name         = "supportedTen"
  value        = var.supportedTen
  key_vault_id = azurerm_key_vault.vault.id
  expiration_date = timeadd(timestamp(), "2160h")
  depends_on = [azurerm_key_vault_access_policy.vault]
}

2nd terraform apply onwards-

  # azurerm_key_vault_secret.supportedTenants will be updated in-place
  ~ resource "azurerm_key_vault_secret" "supportedTen" {
      ~ expiration_date = "2021-10-10T19:45:05Z" -> (known after apply)
        id              = "https://uri/secrets/supportedTen/abcde-secret-version"
        key_vault_id    = "/subscriptions/subscriptionid/resourceGroups/resourcegroup--id/providers/Microsoft.KeyVault/vaults/test-kv-dev"
        name            = "supportedTenants"
        tags            = {}
        value           = (sensitive value)
        version         = "abcde-secret-version"
        lifecycle {
           ignore_changes = [
               not_before_date,
               expiration_date
           ]
        }
    }

Using lifecycle meta argument with expiration date can cause issues when you want to actually update the key vault secret expiration date.

A better solution would be to use the Terraform Time provider's time_static() function instead of timestamp() as the time is then stored in the Terraform state.

resource "time_static" "example" {}

output "current_time" {
  value = time_static.example.rfc3339
}
Related