Cloud can be tricky sometimes. Find out what scenarios we've ran into that are worth being mentioned and explained.
Security is a critical aspect of Infrastructure-as-Code (IaC). Hardcoding sensitive information such as passwords, API keys, or personal access tokens in your source code is a major security risk. Instead, Azure Key Vault provides a secure way to store and manage secrets.
In this guide, we’ll cover:
✔ How to retrieve a secret from an existing Azure Key Vault
✔ Using the getSecret() method in Azure Bicep
✔ Ensuring secrets are securely accessed in a virtual machine deployment
✔ Best practices to avoid exposing secrets
_______________________________________________________________________________
Why Use Azure Key Vault for Secrets?
Azure Key Vault is a managed security service that stores secrets, certificates, and encryption keys. By integrating it into Azure Bicep, you can:
✔ Prevent accidental leaks of sensitive information
✔ Centralize secret management for multiple resources
✔ Enhance security by restricting access using managed identities
Instead of storing passwords or API keys directly in Bicep templates, we retrieve them securely from Key Vault.
_______________________________________________________________________________
Retrieving a Secret from an Existing Key Vault
In this example, we have an existing Key Vault (kv-production-secure), which contains a stored secret (vmAdminPassword). Our goal is to retrieve this secret and pass it to an Azure Virtual Machine as the admin password.
1. Reference the Existing Key Vault
To retrieve secrets, we first need to reference the Key Vault in Bicep using the existing keyword.
@description('Subscription ID where the Key Vault exists')
param parSubscriptionId string
@description('Resource Group containing the Key Vault')
param parResourceGroupName string
@description('Name of the existing Key Vault')
param parKeyVaultName string
resource resKeyVault 'Microsoft.KeyVault/vaults@2021-11-01-preview' existing = {
name: parKeyVaultName
scope: resourceGroup(parSubscriptionId, parResourceGroupName)
}
@description('Name of the secret in Key Vault')
param parSecretName string
var varAdminPassword = resKeyVault.getSecret(parSecretName)
module modVirtualMachine 'vm.bicep' = {
name: 'deploy-vm-secure'
params: {
adminPassword: varAdminPassword
}
}
output outAdminPassword string = varAdminPassword // ❌ This will fail
resource resKeyVaultAccess 'Microsoft.Authorization/roleAssignments@2020-10-01' = {
name: guid(resourceGroup().id, 'KeyVaultSecretReader')
scope: resKeyVault
properties: {
roleDefinitionId: '/subscriptions/${parSubscriptionId}/providers/Microsoft.Authorization/roleDefinitions/b86a8fe4-44ce-4948-aee5-eccb2c155cd7' // Key Vault Secrets Reader Role
principalId: ''
}
}
Conclusion