Tuesday, September 29, 2020

Azure: Encrypting VM disks with Powershell using Azure key vault

 Encrypting disks in Azure for virtual machines can be a good idea if you have sensitive data on them. At current client the decision is to encrypt disks for domain controllers but not for general purpose VMs (as it adds a bit of administrative overhead and might impact performance - I don't have specific numbers on this).

If you have a key vault in place with the -EnabledForDiskEncryption parameter set it is relatively easy to configure on the VM. The VM has to be already running so it is a post step after install.

From the VM deploy script you can add the below code snippet to your script:

# Encrypt VM disks (should only be done for AD VMs and VMs with highly sensitive data)
Write-host "Checking if disks are encrypted on VM"

# Get key vault
$KeyVault = Get-AzKeyVault -VaultName $kvname -ResourceGroupName $secrgname

# Check if disk already encrypted, if not then encrypt it
if (Get-AzVmDiskEncryptionStatus -VMName $VMName -ResourceGroupName $ResourceGroupName | Where-Object {$_.OsVolumeEncrypted -eq "Encrypted"}){
    Write-host "Disk already encrypted"
else {
    Write-host "Encrypting disks"
    Set-AzVMDiskEncryptionExtension -ResourceGroupName $ResourceGroupName `
     -VMName $VMName `
     -DiskEncryptionKeyVaultUrl $KeyVault.VaultUri `
     -DiskEncryptionKeyVaultId $KeyVault.ResourceId `


  • $kvname: Name of the key vault
  • $secrgname: Name of the resource group where key vault resides
  • $VMName: Name of the VM
  • ResourceGroupName: Name of resource group where VM resides
Assuming you have the correct permissions set on the key vault, then the secret will be created automatically in the key vault. During the encrypt process the VM will reboot and it takes about 10 minutes depending on the size of the disks.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.