3/8/2017 - 4:05 PM

Encrypt Azure VM Disks with PowerShell

Encrypt Azure VM Disks with PowerShell


  Enables disk encrption on a VM

  Enables disk encryption on a VM. The script will create a new Key Vault, Azure Active Directory Application and Service principal
  .PARAMETER ResourceGroupName
  The name of the resource group that contains the key vault and virtual machine
  .PARAMETER Location
  The location of the resources
  The name of the virtual machine
  .PARAMETER KeyVaultName
  The name of the key vault. A new key vault will be created if it doesn't exist
  .PARAMETER AADClientSecret
  The client secret used by the Azure AD Application

  $AAdClientSecret = "S3cr3t123!" | ConvertTo-SecureString -AsPlainText -Force
  .\ConfigureVMDiskEncryption.ps1 -ResourceGroupName "ResourceGroup01" -Location "UK South" -VMName "VM01" -KeyVaultName "KeyVault01" -AAdClientSecret $AAdClientSecret -Verbose







# -- Retrieve or create a new Key Vault that is enabled for disk encryption
$KeyVault = Get-AzureRmKeyVault -ResourceGroupName $ResourceGroupName -VaultName $KeyVault -Verbose:$VerbosePreference -ErrorAction SilentlyContinue

if (!$KeyVault) {
    Write-Verbose -Message "Key Vault $($KeyVaultName) does not exist. Creating.."
    $KeyVault = New-AzureRmKeyVault -VaultName $KeyVaultName -ResourceGroupName $ResourceGroupName -Location $Location -Verbose:$VerbosePreference

Set-AzureRmKeyVaultAccessPolicy -ResourceGroupName $ResourceGroupName -VaultName $KeyVaultName -EnabledForDiskEncryption -Verbose:$VerbosePreference

# --- Create an AzureADApplication and a new service principal
$AAdApplicationParameters = @{
    DisplayName = $KeyVaultName
    HomePage = $KeyVault.VaultUri
    IdentifierUris = $KeyVault.VaultUri
    Password = $AAdClientSecret
$AadApplication = New-AzureRmADApplication @AadApplicationParameters -Verbose:$VerbosePreference
$ServicePrincipal = New-AzureRmADServicePrincipal –ApplicationId $AadApplication.ApplicationId -Verbose:$VerbosePreference

# --- Allow the application access to the Key Vault
$KeyVaultAccessPolicyParameters = @{
    ResourceGroupName = $ResourceGroupName
    VaultName = $keyVaultName
    ServicePrincipalName = $AadApplication.ApplicationId
    PermissionsToKeys = "WrapKey"
    PermissionsToSecrets = "Set"

Set-AzureRmKeyVaultAccessPolicy @KeyVaultAccessPolicyParameters -Verbose:$VerbosePreference

# --- Encrypt the disks
$DiskEncryptionExtensionParameters = @{
    ResourceGroupName = $ResourceGroupName
    VMName = $VMName
    AadClientID = $AadApplication.ApplicationId
    AadClientSecret = $AadClientSecret
    DiskEncryptionKeyVaultUrl = $KeyVault.VaultUri
    DiskEncryptionKeyVaultId = $KeyVault.ResourceId

Set-AzureRmVMDiskEncryptionExtension @DiskEncryptionExtensionParameters -Verbose:$VerbosePreference