Just encrypt the virtual machine Azure

Ran into an issue trying to encrypt the disks of a new VM in Azure. After running the cmdlet to encrypt the disks the vm would reboot and then Azure would stop it. Never figured out why, I ended up rebuilding it with new disks and creating a new script from a different Azure doc. Such is life in the cloud. Also, I don’t know what I’m doing. This script creates a new keyvault, new AAD service principle, and then encrypts an existing VM. Make sure to replace the variables.


#Login and select your subscription
Login-AzureRmAccount
Select-AzureRmSubscription -SubscriptionName "Meh"

#Create KeyVault
$rgName = "meh"
$location = "meh"
Register-AzureRmResourceProvider -ProviderNamespace "Microsoft.KeyVault"
$keyVaultName = "meh"
New-AzureRmKeyVault -Location $location `
-ResourceGroupName $rgName `
-VaultName $keyVaultName `
-EnabledForDiskEncryption
Add-AzureKeyVaultKey -VaultName $keyVaultName `
-Name "meh" `
-Destination "Software"

#Create AAD service principal
$appName = "meh"
$securePassword = "SuperSecretStrongM3h"
$app = New-AzureRmADApplication -DisplayName $appName `
-HomePage "https://meh.meh.com" `
-IdentifierUris "https://meh.com/meh" `
-Password $securePassword
New-AzureRmADServicePrincipal -ApplicationId $app.ApplicationId
Set-AzureRmKeyVaultAccessPolicy -VaultName $keyvaultName `
-ServicePrincipalName $app.ApplicationId `
-PermissionsToKeys "WrapKey" `
-PermissionsToSecrets "Set"

#Encrypt VM
$vmName = "meh-vm"
$keyname = "meh-kv-secret"
$keyVault = Get-AzureRmKeyVault -VaultName $keyVaultName -ResourceGroupName $rgName;
$diskEncryptionKeyVaultUrl = $keyVault.VaultUri;
$keyVaultResourceId = $keyVault.ResourceId;
$keyEncryptionKeyUrl = (Get-AzureKeyVaultKey -VaultName $keyVaultName -Name $keyname).Key.kid;

Set-AzureRmVMDiskEncryptionExtension -ResourceGroupName $rgName `
-VMName $vmName `
-AadClientID $app.ApplicationId `
-AadClientSecret $securePassword `
-DiskEncryptionKeyVaultUrl $diskEncryptionKeyVaultUrl `
-DiskEncryptionKeyVaultId $keyVaultResourceId `
-KeyEncryptionKeyUrl $keyEncryptionKeyUrl `
-KeyEncryptionKeyVaultId $keyVaultResourceId

Get-AzureRmVmDiskEncryptionStatus -ResourceGroupName $rgName -VMName $vmName

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.