Preserving Azure Key Vault access policies when recreating with Bicep
While RBAC roles are the preferred access control method for Key Vaults, there are still projects where you need to work with access policies, where a Managed Identity is given specific permissions to the Key Vault.
In the latter case, a common challenge arises when recreating a Key Vault with Bicep - you lose all existing access policies. This phenomenon is documented in this GitHub issue.
In this article, you will find a simple trick to preserve and reapply them during deployment.
Step 1: Check if the Key Vault Exists
First, use the Azure CLI to check if the Key Vault already exists:
az keyvault show --name <key-vault-name> --resource-group <resource-group-name>
Step 2: Reference Existing Access Policies in Bicep
In your Bicep template, use the reference
function to get the existing access policies:
param keyVaultName string
param keyVaultExists bool = false
resource keyVault 'Microsoft.KeyVault/vaults@2024-11-01' = {
name: keyVaultName
location: location
properties: {
// ... other properties
accessPolicies: keyVaultExists ? reference(resourceId('Microsoft.KeyVaults/vaults', keyVaultName), '2024-11-01').accessPolicies : []
}
}
- If the Key Vault exists: The
reference
function retrieves the current access policies and reapplies them - If the Key Vault doesn’t exist: An empty array is used, creating a fresh Key Vault without access policies
Step 3: Deploy with Conditional Logic
When deploying, pass the keyVaultExists
parameter:
# If Key Vault exists
az deployment group create \
--resource-group <resource-group-name> \
--template-file main.bicep \
--parameters keyVaultName=<key-vault-name> keyVaultExists=true
# If Key Vault doesn't exist
az deployment group create \
--resource-group <resource-group-name> \
--template-file main.bicep \
--parameters keyVaultName=<key-vault-name> keyVaultExists=false
Conclusion
This approach ensures that existing access policies are preserved when recreating a Key Vault, preventing service disruptions and maintaining security configurations.