
Azure Key VaultAuthorCloudBrum editorial teamLast reviewedReading time~12 minLevelBeginner to advanced
Microsoft Azure · Security · Keys, secrets and certificates
One vault for the keys, the passwords and the certificates your apps depend on. Key Vault stores three kinds of object behind one access model: cryptographic keys, secrets such as connection strings, and TLS certificates. Standard vaults protect keys with software, Premium vaults can hold them in hardware security modules, and Managed HSM gives you a dedicated pool. New vaults created with the 2026-02-01 API version or later default to Azure RBAC, so check which model an older template or a tutorial still assumes.
On this page (17 sections)
Mind map: Azure Key Vault at a glance
Free to share. The downloaded image includes the CloudBrum link.
Key features (summary)
- Keys, secrets and certificates togetherKeys do the encrypting and signing without leaving the vault. Secrets hold values up to 25 KB, such as passwords and connection strings. Certificates are stored with their private key and can be issued and renewed for you.
- Three levels of protectionStandard vaults protect keys in software. Premium vaults can create keys in HSMs. Managed HSM is a separate service with a single-tenant pool that you own and size.
- Azure RBAC for the data planeBuilt-in roles such as Key Vault Secrets User, Crypto User and Crypto Officer separate who may read secrets, use keys or manage them. Roles can sit at the vault, resource group or subscription level.
- Rotation and renewalA rotation policy creates a new key version on a schedule, and certificates can renew automatically with integrated certificate authorities. Events tell you when something is about to expire.
- Soft delete and purge protectionDeleted vaults and objects stay recoverable for 7 to 90 days. Purge protection stops anyone, including an owner, from permanently deleting them before that time runs out.
- Managed identities instead of passwordsAn app on App Service, a VM or AKS can read a secret with its own managed identity, so you don’t need a credential in code to get at the other credentials.
- Customer-managed keys for Azure servicesStorage accounts, Azure SQL, managed disks, Cosmos DB and many others can encrypt their data with a key from your vault or Managed HSM instead of a Microsoft-managed one.
- Logs and policyDiagnostic settings send every request to Log Analytics or storage, and Azure Policy has built-in definitions for soft delete, purge protection, rotation policies and network access.
Basic concepts
- Vault
- The container for keys, secrets and certificates. It lives in one region and has its own URL, access model and network rules.
- Key
- A cryptographic key, either generated in the vault or imported. Operations such as sign, verify, wrap, unwrap, encrypt and decrypt are performed by the vault, so the private part of the key normally stays inside it.
- Secret
- Any small sensitive value, such as a password, token or connection string, stored as text up to 25 KB. Each new value creates a new version.
- Certificate
- A certificate with its private key, along with a policy that says how it’s issued and renewed. Key Vault stores it and can also request it from a certificate authority.
- Management plane and data plane
- The management plane creates and configures vaults through Azure Resource Manager. The data plane reads and uses keys, secrets and certificates. The two are authorised separately.
- Azure RBAC
- Role-based access control through Microsoft Entra ID. For Key Vault it covers the data plane when the vault is set to the RBAC permission model.
- Access policy
- The older, vault-level list of who may do what. It’s still supported, and a management-plane Contributor can edit it, which is the usual reason to move to RBAC.
- Managed identity
- An identity that Azure creates and rotates for a resource, so the resource can sign in to Entra ID without a stored password.
- Soft delete
- A protection that keeps deleted vaults and objects for a retention period (7 to 90 days) so they can be recovered.
- Purge protection
- A setting that blocks permanent deletion until the retention period ends. Once it’s on, it can’t be turned off.
- HSM-protected key
- A key created and used inside a hardware security module, available in Premium vaults and in Managed HSM.
- Managed HSM
- A separate service that gives you a single-tenant, highly available HSM pool, controlled through its own local RBAC.
- Key rotation policy
- A rule on a key that creates a new version on a schedule and can send a notification before the key expires.
How to create & configure it
Create a vault and use it from an app with the Azure CLI
- Choose a region and a tierPick a region close to the apps that will call the vault, and decide whether Standard is enough. Choose Premium if a rule demands HSM-protected keys, and look at Managed HSM only when you need a dedicated pool.
- Create the vault with the safe settingsUse the RBAC permission model, keep soft delete on, turn on purge protection for anything real, and disable public network access once a private endpoint is ready.
- Add the private endpointCreate a private endpoint and a private DNS zone (privatelink.vaultcore.azure.net) in the network where the apps run, so the vault name resolves to a private address.
- Give people and apps rolesAssign roles at the vault scope: Key Vault Secrets User to an app that reads secrets, Key Vault Crypto User to one that uses keys, and an administrator role to a small group. Avoid giving roles higher up than you need.
- Put objects inCreate a key with an expiry date and a rotation policy, set secrets with an expiry, and import or request a certificate with an auto-renew policy.
- Read them from the app with a managed identityEnable a managed identity on the app, give it the right role and use DefaultAzureCredential in the SDK. Don’t copy the secret into settings.
- Wire up logging and alertsSend the AuditEvent log to Log Analytics, and alert on failed requests, vault deletions and role changes. Subscribe to the near-expiry events with Event Grid.
- Apply policyAssign Azure Policy definitions that require soft delete, purge protection, RBAC, a rotation policy and no public access, in audit mode first.
- Practise recoveryDelete a test secret, recover it, and rehearse restoring a vault. Know the retention period and who holds the role that can purge.
Tip: the portal’s quick-create page often leaves public access on and purge protection off. Use the CLI or a template for production vaults so the settings are written down. See the code references for the same setup as Terraform.
Common issues after configuration
| Symptom | Likely cause | What to check / fix |
|---|---|---|
| Forbidden or The user, group or application does not have secrets get permission on key vault | The vault uses RBAC and the identity has no data-plane role, or it uses access policies and the policy was never added | Check the vault’s permission model, then assign Key Vault Secrets User (or the right role) at the vault scope. Role assignments can take several minutes to apply. |
| ForbiddenByFirewall or Client address is not authorized | The vault has a firewall or public access disabled, and the caller isn’t coming through an allowed network or private endpoint | Add the private endpoint, or allow the caller’s network. For a quick test add your address, and remove it afterwards. |
| 429 Too Many Requests | The vault’s transaction limit was reached, often by an app that reads a secret on every request | Cache secrets in memory, read them at start-up, use the SDK’s retry settings, and spread very busy workloads over several vaults. |
| VaultAlreadyExists or a name that can’t be reused | A deleted vault in soft-deleted state still holds the name, and purge protection stops you from purging it | Recover the vault, or wait for the retention period. Plan vault names, since they’re global. |
| A secret or key was deleted by mistake | Someone with delete permission removed it | Recover it from the soft-deleted list (az keyvault secret recover), and limit delete and purge roles. |
| A certificate didn’t renew | The issuer isn’t integrated, the policy’s lifetime action is missing, or the account for the CA is invalid | Check the certificate’s issuer and policy, read the pending operation’s status, and add an alert on the near-expiry event. |
| Customer-managed key setup fails for Storage or SQL | Soft delete or purge protection is off, the service’s identity has no Crypto Service Encryption User role, or the key is in another region or tenant | Turn on both protections, grant the role to the service’s managed identity and use a key of a supported type and size. |
| The app gets an old secret value | It cached the first version, or it asks for a specific version | Request the latest version by name, and refresh the cache on a timer or when the near-expiry or new-version event fires. |
| Operation not permitted when listing vaults across subscriptions | A management-plane role is in place, but the data-plane role isn’t | Reading a vault’s settings and reading its secrets are different permissions, so assign both where needed. |
| A template or tutorial that creates access policies stops working | From API version 2026-02-01 a new vault defaults to Azure RBAC, so the policies the template writes are ignored | Set enableRbacAuthorization explicitly in your template, and move to role assignments if you can. |
| A key can’t be used for the operation you tried | The key type or its allowed operations don’t include it, or it has expired or isn’t active yet | Look at the key’s attributes (not before, expires, key_ops), and create a key with the right type and operations. |
Use cases: when and where to use it
Good fit
- Teams on Azure that need one place for secrets, keys and certificates with audit logs
- Apps on App Service, Functions, AKS or VMs that should read credentials with a managed identity
- Storage, SQL or disk encryption under a customer-managed key
- Signing and encryption keys that need a hardware boundary (Premium or Managed HSM)
- Certificate lifecycle for services that use a supported certificate authority
- Organisations that need to prove who accessed which secret and when
Consider something else
- Encryption keys only, in a flat, account-wide model → AWS KMS or Cloud KMS
- A dedicated, customer-controlled HSM with its own admin model → Managed HSM, or Azure Cloud HSM
- Application configuration that isn’t secret → Azure App Configuration
- Identity for people and apps → Microsoft Entra ID, which Key Vault uses for sign-in
- The same job on other clouds → compare AWS Secrets Manager with AWS KMS, and Google’s Secret Manager with Cloud KMS
Pros: why consider it?
Why teams choose it
- Keys, secrets and certificates in one service and one access model
- Azure RBAC and managed identities remove most stored credentials
- Soft delete and purge protection guard against deletion
- Wide support as the key source for customer-managed encryption across Azure
- Clear tiers from software to a dedicated HSM pool
- Diagnostic logs and Azure Policy built in
Trade-offs to weigh
- Throttling limits per vault can catch chatty apps
- The management plane and the data plane are separate, which confuses newcomers
- Old tutorials use access policies, while new vaults default to RBAC
- Purge protection is permanent once it’s on
- Managed HSM is billed by the hour for every pool you run
- Vault names are global and recovery rules affect reuse
Common threats, vulnerabilities & risks
| Risk | Severity | Why it matters | Mitigation |
|---|---|---|---|
| Public network access left on | High | The vault’s endpoint is reachable from the internet, so the only control left is identity. | Use a private endpoint, disable public access and allow named networks only where needed. |
| Broad role assignments at subscription scope | High | A person or app with a data role at a high scope can read or use every vault below it. | Assign roles at the vault, review them regularly and use groups with just-in-time elevation. |
| Legacy access policies with wide Contributor rights | High | A management-plane Contributor can add an access policy for themselves and read secrets. | Move to the RBAC model and restrict who has Owner, Contributor and User Access Administrator. |
| Secrets without expiry or rotation | Medium | A leaked secret works forever, and nobody notices it getting old. | Set expiry dates, rotate through automation and alert on near-expiry events. |
| Purge protection off on a vault used for encryption keys | Medium | Someone could permanently delete the key, and the encrypted data would be lost. | Turn on purge protection for any vault behind customer-managed keys. |
| Secrets read on every request | Medium | The app hits the vault limit, gets 429 errors and may take an outage with it. | Cache values in memory and refresh on a schedule or on an event. |
| One vault for everything | Medium | A single vault is one throttling domain and a large blast radius for mistakes. | Use separate vaults per application and environment, and a separate one for encryption keys. |
| No logging on the vault | Low–Med | You can’t tell who read a secret or when the role assignments changed. | Turn on diagnostic settings to Log Analytics and keep the logs for the period your rules require. |
| Unrehearsed recovery | Low–Med | The first recovery attempt happens during an incident. | Practise recovering a soft-deleted object, and write down who may purge and how. |
Performance optimisation
- Cache secrets in memory and refresh them on a timer or an event, rather than reading on every request.
- Read secrets at start-up, and use the SDK’s built-in retry policy for 429 and transient errors.
- Use key references in App Service and Functions settings, so the platform fetches the value and rotates it for you.
- Keep vaults close to the app’s region, and use a private endpoint to avoid a longer network path.
- For high-volume encryption, wrap a data key with the vault key and encrypt locally, rather than sending every payload to the vault.
- Spread busy workloads across several vaults, because the transaction limits apply to each vault in a region.
- Use RSA 2048 or ECC P-256 where your policy allows, because larger RSA keys have much lower limits per vault.
- Avoid creating objects in a loop; create operations have a far lower limit than reads.
Reduce monthly cost
FinOps is the habit of managing cloud spend together with engineering. These are the FinOps checks that matter most for Azure Key Vault.
- Remember that operations, not objects, are the main charge for secrets and software keys, so caching helps your bill as well as your performance.
- Use Standard unless a rule needs HSM-protected keys, since Premium adds a per-key charge for HSM keys.
- Look hard at Managed HSM, which is billed by the hour for each pool, and use it only where a dedicated HSM is required.
- Limit HSM-protected key counts by using fewer keys with wrapping, not a key per record.
- Watch certificate renewals, which are billed per request for integrated certificate authorities.
- Avoid polling a vault from many instances, and use events to refresh.
- Delete unused vaults and keys, and remember that soft-deleted items still hold a name.
- Use private endpoints only where needed, since each endpoint and its data processing is billed.
- Check diagnostic log volume: Log Analytics ingestion is billed on top of the vault, and a busy vault writes a lot of audit events.
- Tag vaults with an owner and a project, and add a budget alert on Key Vault spend.
Prices come from Microsoft's pricing page and secondary sources as we read them in October 2026. Sources disagree on some figures, and they differ by region and change over time. Check the live page before you plan around them (see Pricing).
Security optimisation
- Use the Azure RBAC permission model, give each app the narrowest role (for example Key Vault Secrets User) and assign it at the vault.
- Use managed identities and DefaultAzureCredential, and don’t put client secrets in settings.
- Turn on purge protection (soft delete is on already) for production vaults and any vault behind customer-managed keys.
- Use a private endpoint and disable public network access, or allow only named networks.
- Set expiry dates on secrets and keys, add rotation policies and alert on near-expiry events.
- Use Premium or Managed HSM where a rule requires hardware protection of the key.
- Separate vaults by application and environment, and keep encryption keys apart from application secrets.
- Send the AuditEvent logs to Log Analytics, and alert on failed access, role changes and deletes.
- Review who has Owner, Contributor and User Access Administrator, because they can change who reaches the data.
- Assign Azure Policy definitions for soft delete, purge protection, RBAC, rotation and network access, and review the results.
Governance & compliance
Guardrails
- A Bicep or Terraform module for vaults with RBAC, purge protection, a private endpoint, diagnostic logs and tags
- Azure Policy at the management group that denies vaults with public access or without purge protection
- A rule for who holds the roles that can purge, manage keys or assign access, reviewed on a schedule
- A secret and key expiry standard (for example every key has an expiry and a rotation policy) with an owner for each vault
Continuous checks (Azure Policy and Defender for Cloud)
- “Key vaults should have soft delete enabled” and “should have purge protection enabled”
- “Azure Key Vault should use RBAC permission model”
- “Azure Key Vault should disable public network access”
- “Keys should have a rotation policy” and “should have an expiration date”
- Defender for Cloud recommendations and alerts for unusual vault access
Diagnostic logs record each data-plane request, Azure Policy evaluates the rules above, Defender for Cloud raises alerts and recommendations, and the Microsoft Service Trust Portal holds audit reports. Microsoft operates the service and, for Premium and Managed HSM, the HSMs, which Microsoft says carry a FIPS 140-3 Level 3 validation. You own the access model, network rules, expiry and rotation settings, and the decision to purge.
Reduce carbon footprint
- Cache secrets in memory, so fewer calls cross the network to the vault.
- Use events instead of polling to refresh values.
- Delete unused vaults, keys and old certificate versions.
- Keep diagnostic logs to what you need, and set a retention period.
- Where data rules allow and latency doesn’t matter, pick a region with a cleaner power grid.
- Microsoft’s Emissions Impact Dashboard gives emission estimates by subscription. Key Vault usage isn’t itemised, so don’t quote a figure for it.
Pricing
Purchase options
Standard vault Per 10,000 operations
Secrets, certificates and software-protected keys are billed by operation. Software keys carry no per-key fee in the sources we read.
Premium vault Operations plus HSM key fees
HSM-protected keys add a monthly fee for each key, and their operations can cost more. Sources disagree on current rates.
Certificates Per renewal
Certificates requested through an integrated certificate authority are billed for each renewal, in addition to the authority’s own fees.
Managed HSM Per hour for each HSM pool
A pool is billed by the hour. A third-party summary lists the Standard B1 pool at about $3.20 an hour, which is roughly $2,300 a month.
What you actually pay for
- Operations on keys, secrets and certificates
- Monthly fees for HSM-protected keys in Premium vaults
- Managed HSM pools, by the hour
- Certificate renewals through integrated authorities
- Private endpoints, Log Analytics ingestion and storage for logs
Rates differ by region and sources disagree on several figures. See the official Azure Key Vault pricing page and the Azure pricing calculator.
Important code references
A vault for an orders service: RBAC permission model, purge protection, no public access, a private endpoint, an app identity that may read secrets and use one key, a key with a rotation policy and an expiry, and audit logs sent to Log Analytics. The Azure CLI tab creates it and Terraform builds the same set. The Python tab does envelope encryption: it wraps a random data key with the vault key and encrypts locally, and the C# tab audits the keys and secrets in a vault for missing expiry, rotation policy and nearing expiry. Replace the names, region and subnet with your own. Vault names are global, so yours must be unique.
# Placeholders: replace the names, region, subnet and Log Analytics workspace with your own. Vault names are global.
RG=rg-orders-prod
LOC=centralindia
VAULT=kv-orders-prod-4821
VNET=vnet-orders
SUBNET=snet-private-endpoints
WORKSPACE=/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg-monitor/providers/Microsoft.OperationalInsights/workspaces/law-central
az group create --name $RG --location $LOC
# 1. The vault: RBAC permission model, soft delete (always on), purge protection, no public access.
az keyvault create --name $VAULT --resource-group $RG --location $LOC --sku premium \
--enable-rbac-authorization true --enable-purge-protection true --retention-days 90 \
--public-network-access Disabled
VAULT_ID=$(az keyvault show --name $VAULT --resource-group $RG --query id -o tsv)
# 2. A private endpoint and the private DNS zone, so the vault name resolves to a private address.
az network private-endpoint create --name pe-$VAULT --resource-group $RG --vnet-name $VNET --subnet $SUBNET \
--private-connection-resource-id $VAULT_ID --group-id vault --connection-name kv-link
az network private-dns zone create --resource-group $RG --name privatelink.vaultcore.azure.net
az network private-dns link vnet create --resource-group $RG --zone-name privatelink.vaultcore.azure.net \
--name kv-dns-link --virtual-network $VNET --registration-enabled false
az network private-endpoint dns-zone-group create --resource-group $RG --endpoint-name pe-$VAULT --name default \
--private-dns-zone privatelink.vaultcore.azure.net --zone-name vault
# 3. Roles: an admin group manages objects, the app identity reads secrets and uses one key.
ADMINS=$(az ad group show --group "orders-key-admins" --query id -o tsv)
APP_ID=$(az identity create --name id-orders-app --resource-group $RG --query principalId -o tsv)
az role assignment create --assignee-object-id $ADMINS --assignee-principal-type Group --role "Key Vault Administrator" --scope $VAULT_ID
az role assignment create --assignee-object-id $APP_ID --assignee-principal-type ServicePrincipal --role "Key Vault Secrets User" --scope $VAULT_ID
# From here on the commands talk to the vault's data plane. With public access off, run them from inside the network, or add your own IP to the firewall for the first run.
# 4. A key with an expiry and a rotation policy: new version after 90 days, notify 30 days before expiry.
az keyvault key create --vault-name $VAULT --name orders-data-key --kty RSA --size 3072 --protection hsm \
--ops wrapKey unwrapKey --expires "$(date -u -d '+2 years' +%Y-%m-%dT%H:%M:%SZ)"
cat > rotation.json <<'EOF'
{
"lifetimeActions": [
{"trigger": {"timeAfterCreate": "P90D"}, "action": {"type": "Rotate"}},
{"trigger": {"timeBeforeExpiry": "P30D"}, "action": {"type": "Notify"}}
],
"attributes": {"expiryTime": "P2Y"}
}
EOF
az keyvault key rotation-policy update --vault-name $VAULT --name orders-data-key --value @rotation.json
KEY_ID=$(az keyvault key show --vault-name $VAULT --name orders-data-key --query key.kid -o tsv)
az role assignment create --assignee-object-id $APP_ID --assignee-principal-type ServicePrincipal --role "Key Vault Crypto User" --scope "$VAULT_ID/keys/orders-data-key"
# 5. A secret with an expiry.
az keyvault secret set --vault-name $VAULT --name db-connection --value "Server=...;Password=placeholder" \
--expires "$(date -u -d '+90 days' +%Y-%m-%dT%H:%M:%SZ)"
# 6. Audit logs to Log Analytics.
az monitor diagnostic-settings create --name kv-audit --resource $VAULT_ID --workspace $WORKSPACE \
--logs '[{"category": "AuditEvent", "enabled": true}]'
# 7. Recovery drill: delete a secret, list the deleted ones, recover it.
az keyvault secret delete --vault-name $VAULT --name db-connection
az keyvault secret list-deleted --vault-name $VAULT --query "[].name"
az keyvault secret recover --vault-name $VAULT --name db-connection
# Placeholders: pass in your own names, subnet and workspace. Vault names are global.
terraform {
required_providers {
azurerm = {
source = "hashicorp/azurerm"
version = "~> 4.0"
}
}
}
provider "azurerm" {
features {}
}
variable "location" {
type = string
default = "centralindia"
}
variable "vault_name" {
type = string
default = "kv-orders-prod-4821"
}
variable "private_endpoint_subnet_id" {
type = string
}
variable "log_analytics_workspace_id" {
type = string
}
variable "admin_group_object_id" {
type = string
}
data "azurerm_client_config" "current" {}
resource "azurerm_resource_group" "orders" {
name = "rg-orders-prod"
location = var.location
}
resource "azurerm_key_vault" "orders" {
name = var.vault_name
location = azurerm_resource_group.orders.location
resource_group_name = azurerm_resource_group.orders.name
tenant_id = data.azurerm_client_config.current.tenant_id
sku_name = "premium"
rbac_authorization_enabled = true
purge_protection_enabled = true
soft_delete_retention_days = 90
public_network_access_enabled = false
network_acls {
default_action = "Deny"
bypass = "AzureServices"
}
}
resource "azurerm_private_endpoint" "vault" {
name = "pe-${var.vault_name}"
location = azurerm_resource_group.orders.location
resource_group_name = azurerm_resource_group.orders.name
subnet_id = var.private_endpoint_subnet_id
private_service_connection {
name = "kv-link"
private_connection_resource_id = azurerm_key_vault.orders.id
subresource_names = ["vault"]
is_manual_connection = false
}
}
resource "azurerm_user_assigned_identity" "app" {
name = "id-orders-app"
location = azurerm_resource_group.orders.location
resource_group_name = azurerm_resource_group.orders.name
}
resource "azurerm_role_assignment" "admins" {
scope = azurerm_key_vault.orders.id
role_definition_name = "Key Vault Administrator"
principal_id = var.admin_group_object_id
}
resource "azurerm_role_assignment" "app_secrets" {
scope = azurerm_key_vault.orders.id
role_definition_name = "Key Vault Secrets User"
principal_id = azurerm_user_assigned_identity.app.principal_id
}
# The person or pipeline that runs this needs a data-plane role before it can create keys.
resource "azurerm_role_assignment" "deployer" {
scope = azurerm_key_vault.orders.id
role_definition_name = "Key Vault Crypto Officer"
principal_id = data.azurerm_client_config.current.object_id
}
resource "azurerm_key_vault_key" "data" {
name = "orders-data-key"
key_vault_id = azurerm_key_vault.orders.id
key_type = "RSA-HSM"
key_size = 3072
key_opts = ["wrapKey", "unwrapKey"]
expiration_date = timeadd(timestamp(), "17520h")
rotation_policy {
automatic {
time_after_creation = "P90D"
}
expire_after = "P2Y"
notify_before_expiry = "P30D"
}
depends_on = [azurerm_role_assignment.deployer]
lifecycle {
ignore_changes = [expiration_date]
}
}
resource "azurerm_role_assignment" "app_key" {
scope = azurerm_key_vault_key.data.resource_versionless_id
role_definition_name = "Key Vault Crypto User"
principal_id = azurerm_user_assigned_identity.app.principal_id
}
resource "azurerm_monitor_diagnostic_setting" "audit" {
name = "kv-audit"
target_resource_id = azurerm_key_vault.orders.id
log_analytics_workspace_id = var.log_analytics_workspace_id
enabled_log {
category = "AuditEvent"
}
}
output "vault_uri" {
value = azurerm_key_vault.orders.vault_uri
}
# pip install azure-identity azure-keyvault-keys azure-keyvault-secrets cryptography
# Envelope encryption: the vault key wraps a random data key, AES-GCM encrypts the payload locally,
# and only the wrapped data key is stored with the ciphertext.
import os
from azure.identity import DefaultAzureCredential
from azure.keyvault.keys import KeyClient
from azure.keyvault.keys.crypto import CryptographyClient, KeyWrapAlgorithm
from azure.keyvault.secrets import SecretClient
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
VAULT_URL = "https://kv-orders-prod-4821.vault.azure.net"
credential = DefaultAzureCredential() # a managed identity in Azure, your az login on a laptop
keys = KeyClient(VAULT_URL, credential)
secrets = SecretClient(VAULT_URL, credential)
def crypto():
key = keys.get_key("orders-data-key") # the latest version
return CryptographyClient(key, credential)
def encrypt(payload, aad):
data_key = AESGCM.generate_key(bit_length=256)
wrapped = crypto().wrap_key(KeyWrapAlgorithm.rsa_oaep_256, data_key)
nonce = os.urandom(12)
return {"key_id": wrapped.key_id, "wrapped_key": wrapped.encrypted_key.hex(), "nonce": nonce.hex(),
"data": AESGCM(data_key).encrypt(nonce, payload, aad).hex()}
def decrypt(envelope, aad):
client = CryptographyClient(keys.get_key("orders-data-key", envelope["key_id"].rsplit("/", 1)[-1]), credential)
data_key = client.unwrap_key(KeyWrapAlgorithm.rsa_oaep_256, bytes.fromhex(envelope["wrapped_key"])).key
return AESGCM(data_key).decrypt(bytes.fromhex(envelope["nonce"]), bytes.fromhex(envelope["data"]), aad)
if __name__ == "__main__":
sealed = encrypt(b'{"order": 1042, "card_last4": "4242"}', b"tenant=acme")
print("stored key id:", sealed["key_id"])
print("read back:", decrypt(sealed, b"tenant=acme").decode())
conn = secrets.get_secret("db-connection") # secrets are read the same way, by name
print("secret expires:", conn.properties.expires_on)
// dotnet add package Azure.Identity
// dotnet add package Azure.Security.KeyVault.Keys
// dotnet add package Azure.Security.KeyVault.Secrets
// Audits one vault: keys and secrets without an expiry, keys without a rotation policy, and anything that expires within 30 days.
using Azure.Identity;
using Azure.Security.KeyVault.Keys;
using Azure.Security.KeyVault.Secrets;
var vaultUri = new Uri(args.Length > 0 ? args[0] : "https://kv-orders-prod-4821.vault.azure.net");
var credential = new DefaultAzureCredential();
var keys = new KeyClient(vaultUri, credential);
var secrets = new SecretClient(vaultUri, credential);
var soon = DateTimeOffset.UtcNow.AddDays(30);
int problems = 0;
void Report(string kind, string name, string message)
{
Console.WriteLine($"{kind,-7} {name,-28} {message}");
problems++;
}
await foreach (KeyProperties key in keys.GetPropertiesOfKeysAsync())
{
if (key.Enabled == false) continue;
if (key.ExpiresOn is null) Report("key", key.Name, "no expiry date");
else if (key.ExpiresOn < soon) Report("key", key.Name, $"expires {key.ExpiresOn:yyyy-MM-dd}");
try
{
KeyRotationPolicy policy = await keys.GetKeyRotationPolicyAsync(key.Name);
if (!policy.LifetimeActions.Any(a => a.Action == KeyRotationPolicyAction.Rotate))
Report("key", key.Name, "rotation policy has no automatic rotate action");
}
catch (Azure.RequestFailedException)
{
Report("key", key.Name, "could not read the rotation policy (missing role, or unsupported key)");
}
}
await foreach (SecretProperties secret in secrets.GetPropertiesOfSecretsAsync())
{
if (secret.Enabled == false) continue;
if (secret.ExpiresOn is null) Report("secret", secret.Name, "no expiry date");
else if (secret.ExpiresOn < soon) Report("secret", secret.Name, $"expires {secret.ExpiresOn:yyyy-MM-dd}");
}
Console.WriteLine(problems == 0 ? "No problems found." : $"{problems} problem(s) found.");
return problems == 0 ? 0 : 1;
Best videos to explore
Videos picked for this service. Each one is labelled with its source, opens on YouTube if you prefer, and loads only when you press play.
Interview questions
BasicWhat is Azure Key Vault?
It’s the Azure service for storing and controlling three kinds of sensitive objects: cryptographic keys, secrets such as passwords and connection strings, and certificates. Apps and people use it through Microsoft Entra ID, and every request can be logged.
BasicWhat is the difference between Standard, Premium and Managed HSM?
Standard vaults protect keys with software. Premium vaults can create keys in hardware security modules. Managed HSM is a separate service that gives you a dedicated, single-tenant pool of HSMs with its own access model. Secrets and certificates work in vaults, and Managed HSM is for keys.
BasicHow does an app get a secret without a password?
It uses a managed identity. Azure gives the app identity to the resource, you assign it a role such as Key Vault Secrets User on the vault, and the SDK’s DefaultAzureCredential signs in as that identity, so no credential is stored in code or settings.
IntermediateAzure RBAC or access policies: which should you use?
Azure RBAC is Microsoft’s recommended model, and it’s the default for new vaults created with API version 2026-02-01 or later. It uses the same role assignment system as the rest of Azure, works at several scopes and can be audited centrally. Access policies still work, but a management-plane Contributor can edit them, so they are easier to misuse.
IntermediateWhat do soft delete and purge protection do?
Soft delete keeps deleted vaults and objects for a retention period of 7 to 90 days so that they can be recovered, and it’s always on. Purge protection prevents permanent deletion during that period, even by an owner. Together they protect against mistakes and malicious deletion, and purge protection can’t be turned off once it’s on.
IntermediateHow do you rotate a secret or a key?
For keys, set a rotation policy so that a new version is created on a schedule, and use Event Grid to tell dependants. For secrets, create a new version and update the consumers, often with an Event Grid-triggered function that also changes the password in the target system. Apps should read the latest version rather than pin one.
AdvancedHow would you handle Key Vault throttling in a busy application?
Cache secrets in memory and refresh them on a timer or an event instead of reading on each request. Use the SDK’s retry policy, which respects 429 responses and their delay. For key operations at volume, wrap a data key with the vault key and do the bulk encryption locally. Split workloads across several vaults, since limits apply per vault per region.
AdvancedHow do customer-managed keys work for Storage or Azure SQL?
The service gets a managed identity, and you give that identity a role such as Key Vault Crypto Service Encryption User on the key. The service wraps its own data encryption key with your key. The vault needs soft delete and purge protection. If you disable or delete the key, or remove the role, the service loses access to its data, so protect the key and monitor it.
AdvancedWhen is Managed HSM the right choice?
Pick it when a rule or contract demands single-tenant HSMs with control of the security domain, when you need higher assurance than a shared vault gives, or when key volume suits a dedicated pool. It’s billed by the hour for each pool and has its own local RBAC and backup model, so for most workloads a Premium vault is simpler and cheaper.
AdvancedWhat breaks when a team moves from access policies to RBAC?
Anything that relied on a policy entry no longer works, because the vault ignores policies once RBAC is on. Plan a role mapping for every identity, assign roles at the vault, test each app, and update templates to set the permission model explicitly. Watch for apps that were given nothing more than list permissions, and check data-plane and management-plane roles together.
Similar or alternative services on other clouds
| Capability | AWS | Azure | Google Cloud |
|---|---|---|---|
| Service | AWS KMS (keys) with Secrets Manager and ACM | Azure Key Vault, and Managed HSM | Cloud KMS with Secret Manager |
| Holds secrets and certificates too | No, separate services | Yes, in the same vault | No, separate services |
| Key containers | Flat, with aliases | Vaults | Key rings, keys and versions |
| Hardware protection | HSMs in the service, plus CloudHSM stores | Premium (HSM-backed) or Managed HSM | Cloud HSM and external key managers |
| Access model | Key policy, IAM and grants | Azure RBAC, or access policies on older vaults | IAM roles |
| Rotation | Automatic, 90 to 2,560 days, or on demand | Rotation policy per key | Rotation schedule per key |
| Deletion safeguards | Waiting period of 7 to 30 days | Soft delete and purge protection | Scheduled destruction of key versions |
| Billing shape | Per key plus requests | Mostly per operation, plus HSM fees | Per key version plus operations |
Apps that read secrets from Key Vault often run on Azure App Service, Azure Functions or Azure Kubernetes Service. Customer-managed keys protect data in Azure Blob Storage and Azure SQL Database.
Did you find this article helpful?
Your answer helps us improve this page for the next reader.
Sources and further reading
CloudBrum wrote this page in its own words, using the provider’s public documentation listed below as the reference. Features, limits, names and prices change, so confirm anything that matters on the provider’s own pages before you decide.
- About Azure Key VaultMicrosoft
- Provide access to Key Vault with Azure RBACMicrosoft
- Default access control for new vaults (API version 2026-02-01)Microsoft
- Azure Key Vault soft delete overviewMicrosoft
- Azure Key Vault service limitsMicrosoft
- Configure key auto-rotation in Azure Key VaultMicrosoft
- Azure Key Vault Managed HSM overviewMicrosoft
- Azure Key Vault pricingMicrosoft
- Terraform azurerm provider: azurerm_key_vaultHashiCorp
