# Customer-managed key for the log storage account. # # Three pieces are needed and each one is easy to forget: a vault with purge # protection, a key, and an identity the storage account uses to reach that key. # The identity is what lets you revoke access by disabling the key, without # touching the data. resource "azurerm_key_vault" "audit" { name = "kv${substr(local.storage_name, 0, 20)}" location = azurerm_resource_group.audit.location resource_group_name = azurerm_resource_group.audit.name tenant_id = data.azurerm_client_config.current.tenant_id sku_name = "standard" # Storage will not accept a key from a vault without purge protection. purge_protection_enabled = true soft_delete_retention_days = 7 rbac_authorization_enabled = true # Closed to the internet like the storage account. Storage reaches the key as # a trusted Azure service, which is what the bypass allows. network_acls { default_action = "Deny" bypass = "AzureServices" ip_rules = var.allowed_ip_ranges } tags = local.tags } # Whoever runs Terraform needs to create the key. On a first apply this role # can take a minute to take effect, and the key creation can fail with 403. # Running apply again is the fix. resource "azurerm_role_assignment" "runner_crypto_officer" { scope = azurerm_key_vault.audit.id role_definition_name = "Key Vault Crypto Officer" principal_id = data.azurerm_client_config.current.object_id } resource "azurerm_key_vault_key" "audit" { name = "${var.name}-storage" key_vault_id = azurerm_key_vault.audit.id key_type = "RSA" key_size = 3072 key_opts = ["wrapKey", "unwrapKey"] tags = local.tags rotation_policy { automatic { time_before_expiry = "P30D" } expire_after = "P1Y" notify_before_expiry = "P29D" } depends_on = [azurerm_role_assignment.runner_crypto_officer] } resource "azurerm_user_assigned_identity" "storage" { name = "id-${var.name}-storage" location = azurerm_resource_group.audit.location resource_group_name = azurerm_resource_group.audit.name tags = local.tags } # The narrowest role that lets the storage account wrap and unwrap with the key. resource "azurerm_role_assignment" "storage_key_user" { scope = azurerm_key_vault.audit.id role_definition_name = "Key Vault Crypto Service Encryption User" principal_id = azurerm_user_assigned_identity.storage.principal_id }