Using time_rotating resource for key rotation on CMKs

Hi, Im trying to use the time_rotating resource to form a part key rotation policy. Whilst it has worked well wrapped around a std key vault resource block, it seems to try to remove the CMK in another block that has conditional logic in it, is there a workaround?

Working example


resource “time_rotating” “key_rotation” {
rotation_days = 7
}

resource “azurerm_key_vault_key” “storage” {
depends_on = [
azurerm_key_vault_access_policy.storage
]

name = var.storage_account_name #azurerm_storage_account.storage.name
key_vault_id = var.keyvault_id
key_type = “RSA”
key_size = 2048

key_opts = [
“decrypt”,
“encrypt”,
“sign”,
“unwrapKey”,
“verify”,
“wrapKey”
]

#Trigger key recreation after defined period by using the time_rotating resource
tags = {
rotation_timestamp = time_rotating.key_rotation.id
}

Problem block


resource “time_rotating” “key_rotation” {
rotation_days = 1
}

resource “azurerm_key_vault_key” “storage” {
count = var.storage_account_name != null ? 1 : 0

#depends_on = [

azurerm_key_vault_access_policy.storage

#]

name = azurerm_storage_account.audit.0.name
key_vault_id = data.azurerm_key_vault.keyvault.id
key_type = “RSA”
key_size = 2048

key_opts = [
“decrypt”,
“encrypt”,
“sign”,
“unwrapKey”,
“verify”,
“wrapKey”
]

Trigger key recreation after defined period by using the time_rotating resource

tags = {
rotation_timestamp = time_rotating.key_rotation.id
}
}

NB: this must be done this way rather than in the storage account as otherwise circular logic applies (due to KeyVault logging to this storage account)

resource “azurerm_storage_account_customer_managed_key” “storage” {
count = var.storage_account_name != null ? 1 : 0

storage_account_id = azurerm_storage_account.audit.0.id
key_vault_id = data.azurerm_key_vault.keyvault.id
key_name = azurerm_key_vault_key.storage.0.name

}

The terraform plan for the 2nd example wants to remove the CMK which I dont want, any ideas on how to get this to work?

Hi @paulgking99,

It would help other if you format the post such that we can distinguish between the text and the configuration, and have the configuration formatted as code so it is properly quoted and indented. For those not familiar with these resources or provider, what is the “CMK”, and what does the plan look like which is going to remove it?

I don’t know if this is what you’re looking for, but if you want to trigger replacement of a resource which does not have a suitable attribute to force the replacement, you can use the replace_triggered_by lifecycle attribute to do this.