使用 Azure PowerShell 加密 Windows 虚拟机Encrypt a Windows virtual machine with Azure PowerShell

此脚本创建安全的 Azure Key Vault、加密密钥、Azure Active Directory 服务主体和 Windows 虚拟机 (VM)。This script creates a secure Azure Key Vault, encryption keys, Azure Active Directory service principal, and a Windows virtual machine (VM). 然后使用 Key Vault 和服务主体凭据中的加密密钥对 VM 进行加密。The VM is then encrypted using the encryption key from Key Vault and service principal credentials.

如果没有 Azure 订阅,可在开始前创建一个试用帐户If you don't have an Azure subscription, create a trial account before you begin.

示例脚本Sample script

# Sign-in the Azure China Cloud
Connect-AzAccount -Environment AzureChinaCloud

# Edit these global variables with you unique Key Vault name, resource group name and location
#Name of the Key Vault
$keyVaultName = "myKeyVault00"
#Resource Group Name
$rgName = "myResourceGroup"
#Region
$location = "China East"
#Password to place w/in the KeyVault
$password = $([guid]::NewGuid()).Guid
$securePassword = ConvertTo-SecureString -String $password -AsPlainText -Force
#Name for the Azure AD Application
$appName = "My App"
#Name for the VM to be encrypt
$vmName = "myEncryptedVM"
#user name for the admin account in the vm being created and then encrypted
$vmAdminName = "encryptedUser"

# Register the Key Vault provider and create a resource group
New-AzResourceGroup -Location $location -Name $rgName

# Create a Key Vault and enable it for disk encryption
New-AzKeyVault `
    -Location $location `
    -ResourceGroupName $rgName `
    -VaultName $keyVaultName `
    -EnabledForDiskEncryption

# Create a key in your Key Vault
Add-AzKeyVaultKey `
    -VaultName $keyVaultName `
    -Name "myKey" `
    -Destination "Software"

# Put the password in the Key Vault as a Key Vault Secret so we can use it later
# We should never put passwords in scripts.
Set-AzKeyVaultSecret -VaultName $keyVaultName -Name adminCreds -SecretValue $securePassword
Set-AzKeyVaultSecret -VaultName $keyVaultName -Name protectValue -SecretValue $securePassword

# Create Azure Active Directory app and service principal
$app = New-AzADApplication -DisplayName $appName `
    -HomePage "https://myapp0.contoso.com" `
    -IdentifierUris "https://contoso.com/myapp0" `
    -Password (Get-AzKeyVaultSecret -VaultName $keyVaultName -Name adminCreds).SecretValue

New-AzADServicePrincipal -ApplicationId $app.ApplicationId

# Set permissions to allow your AAD service principal to read keys from Key Vault
Set-AzKeyVaultAccessPolicy -VaultName $keyvaultName `
    -ServicePrincipalName $app.ApplicationId  `
    -PermissionsToKeys decrypt,encrypt,unwrapKey,wrapKey,verify,sign,get,list,update `
    -PermissionsToSecrets get,list,set,delete,backup,restore,recover,purge

# Create PSCredential object for VM
$cred = New-Object System.Management.Automation.PSCredential($vmAdminName, (Get-AzKeyVaultSecret -VaultName $keyVaultName -Name adminCreds).SecretValue)

# Create a virtual machine
New-AzVM `
  -ResourceGroupName $rgName `
  -Name $vmName `
  -Location $location `
  -ImageName "Win2016Datacenter" `
  -VirtualNetworkName "myVnet" `
  -SubnetName "mySubnet" `
  -SecurityGroupName "myNetworkSecurityGroup" `
  -PublicIpAddressName "myPublicIp" `
  -Credential $cred `
  -OpenPorts 3389

# Define required information for our Key Vault and keys
$keyVault = Get-AzKeyVault -VaultName $keyVaultName -ResourceGroupName $rgName;
$diskEncryptionKeyVaultUrl = $keyVault.VaultUri;
$keyVaultResourceId = $keyVault.ResourceId;
$keyEncryptionKeyUrl = (Get-AzKeyVaultKey -VaultName $keyVaultName -Name "myKey").Key.kid;

# Encrypt our virtual machine
Set-AzVMDiskEncryptionExtension `
    -ResourceGroupName $rgName `
    -VMName $vmName `
    -AadClientID $app.ApplicationId `
    -AadClientSecret (Get-AzKeyVaultSecret -VaultName $keyVaultName -Name adminCreds).SecretValueText `
    -DiskEncryptionKeyVaultUrl $diskEncryptionKeyVaultUrl `
    -DiskEncryptionKeyVaultId $keyVaultResourceId `
    -KeyEncryptionKeyUrl $keyEncryptionKeyUrl `
    -KeyEncryptionKeyVaultId $keyVaultResourceId

# View encryption status
Get-AzVmDiskEncryptionStatus  -ResourceGroupName $rgName -VMName $vmName

<#
#clean up
Remove-AzResourceGroup -Name $rgName
#removes all of the Azure AD Applications you created w/ the same name
Remove-AzADApplication -ObjectId $app.ObjectId -Force
#>

清理部署Clean up deployment

运行以下命令来删除资源组、VM 和所有相关资源。Run the following command to remove the resource group, VM, and all related resources.

Remove-AzResourceGroup -Name myResourceGroup

脚本说明Script explanation

此脚本使用以下命令创建部署。This script uses the following commands to create the deployment. 表中的每一项均链接到特定于命令的文档。Each item in the table links to command specific documentation.

命令Command 注释Notes
New-AzResourceGroupNew-AzResourceGroup 创建用于存储所有资源的资源组。Creates a resource group in which all resources are stored.
New-AzKeyVaultNew-AzKeyVault 创建 Azure Key Vault,存储加密密钥等安全数据。Creates an Azure Key Vault to store secure data such as encryption keys.
Add-AzKeyVaultKeyAdd-AzKeyVaultKey 在 Key Vault 中创建加密密钥。Creates an encryption key in Key Vault.
New-AzADServicePrincipalNew-AzADServicePrincipal 创建 Azure Active Directory 服务主体,安全地进行身份验证并控制对加密密钥的访问。Creates an Azure Active Directory service principal to securely authenticate and control access to encryption keys.
Set-AzKeyVaultAccessPolicySet-AzKeyVaultAccessPolicy 设置对 Key Vault 的权限,授予服务主体访问加密密钥的权限。Sets permissions on the Key Vault to grant the service principal access to encryption keys.
New-AzVMNew-AzVM 创建虚拟机并将其连接到网卡、虚拟网络、子网和网络安全组。Creates the virtual machine and connects it to the network card, virtual network, subnet, and network security group. 此命令还将打开端口 80 并设置管理凭据。This command also opens port 80 and sets the administrative credentials.
Get-AzKeyVaultGet-AzKeyVault 获取有关 Key Vault 的所需信息Gets required information on the Key Vault
Set-AzVMDiskEncryptionExtensionSet-AzVMDiskEncryptionExtension 使用服务主体凭据和加密密钥对 VM 进行加密。Enables encryption on a VM using the service principal credentials and encryption key.
Get-AzVmDiskEncryptionStatusGet-AzVmDiskEncryptionStatus 显示 VM 加密过程的状态。Shows the status of the VM encryption process.
Remove-AzResourceGroupRemove-AzResourceGroup 删除资源组及其中包含的所有资源。Removes a resource group and all resources contained within.

后续步骤Next steps

有关 Azure PowerShell 模块的详细信息,请参阅 Azure PowerShell 文档For more information on the Azure PowerShell module, see Azure PowerShell documentation.

可以在 Azure Windows VM 文档中找到其他虚拟机 PowerShell 脚本示例。Additional virtual machine PowerShell script samples can be found in the Azure Windows VM documentation.