教程:在 ARM 模板部署中集成 Azure Key VaultTutorial: Integrate Azure Key Vault in your ARM template deployment

了解部署 Azure 资源管理器 (ARM) 模版时如何从 Azure 密钥保管库检索机密并将机密作为参数传递。Learn how to retrieve secrets from an Azure key vault and pass the secrets as parameters when you deploy an Azure Resource Manager (ARM) template. 该参数值永远不会公开,因为只会引用其密钥保管库 ID。The parameter value is never exposed, because you reference only its key vault ID. 可以使用静态 ID 或动态 ID 来引用密钥保管库机密。You can reference the key vault secret by using a static ID or a dynamic ID. 本教程使用的是静态 ID。This tutorial uses a static ID. 使用静态 ID 方法,可以在模板参数文件(而不是模板文件)中引用密钥保管库。With the static ID approach, you reference the key vault in the template parameter file, not the template file. 有关这两种方法的详细信息,请参阅在部署过程中使用 Azure Key Vault 传递安全参数值For more information about both approaches, see Use Azure Key Vault to pass secure parameter value during deployment.

设置资源部署顺序教程中,你需要创建虚拟机 (VM)。In the Set resource deployment order tutorial, you create a virtual machine (VM). 需提供 VM 管理员用户名和密码。You need to provide the VM administrator username and password. 可以不提供密码,而是将密码预先存储在 Azure 密钥保管库中,然后自定义模板,以便在部署过程中从密钥保管库检索密码。Instead of providing the password, you can pre-store the password in an Azure key vault and then customize the template to retrieve the password from the key vault during the deployment.

显示具有密钥保管库的资源管理器模板的集成的关系图

本教程涵盖以下任务:This tutorial covers the following tasks:

  • 准备 Key VaultPrepare a key vault
  • 打开快速入门模板Open a quickstart template
  • 编辑参数文件Edit the parameters file
  • 部署模板Deploy the template
  • 验证部署Validate the deployment
  • 清理资源Clean up resources

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

先决条件Prerequisites

若要完成本文,需要做好以下准备:To complete this article, you need:

准备 Key VaultPrepare a key vault

在此部分,创建一个密钥保管库,然后向该密钥保管库添加密钥,这样就可以在部署模板时检索该密钥。In this section, you create a key vault and add a secret to it, so that you can retrieve the secret when you deploy your template. 可以通过许多方法来创建密钥保管库。There are many ways to create a key vault. 在本教程中,我们使用 Azure PowerShell 部署 ARM 模板In this tutorial, you use Azure PowerShell to deploy an ARM template. 此模板执行两项操作:This template does two things:

  • 创建启用了 enabledForTemplateDeployment 属性的密钥保管库。Creates a key vault with the enabledForTemplateDeployment property enabled. 此属性必须为 true,这样模板部署过程才能访问此密钥保管库中定义的机密 。This property must be true before the template deployment process can access the secrets that are defined in the key vault.
  • 将密钥添加到密钥保管库。Adds a secret to the key vault. 该密钥存储 VM 管理员密码。The secret stores the VM administrator password.

备注

如果你(作为要部署虚拟机模板的用户)不是密钥保管库的所有者或参与者,则密钥保管库的所有者或参与者必须向你授予对密钥保管库的 Microsoft.KeyVault/vaults/deploy/action 的访问权限。As the user who's deploying the virtual machine template, if you're not the Owner of or a Contributor to the key vault, the Owner or a Contributor must grant you access to the Microsoft.KeyVault/vaults/deploy/action permission for the key vault. 有关详细信息,请参阅在部署过程中使用 Azure 密钥保管库传递安全参数值For more information, see Use Azure Key Vault to pass a secure parameter value during deployment.

  1. 下载 CreateKeyVault.json 并更新 location 属性,使其与 Azure 中国云匹配。Download the CreateKeyVault.json and update the location property to match the Azure China Cloud.

    1. 在 Visual Studio Code 中,选择“文件” > “打开文件”。 In Visual Studio Code, select File > Open File.

    2. 在“文件名”框中粘贴以下 URL:In the File name box, paste the following URL:

      https://raw.githubusercontent.com/Azure/azure-docs-json-samples/master/tutorials-use-key-vault/CreateKeyVault.json
      

      location 的属性从“centralus”更改为“[parameters('location')]”。Change the property of location from centralus to [parameters('location')].

      备注

      必须修改从 GitHub 存储库“azure-docs-json-samples”下载或引用的模板,使之与 Azure 中国云环境匹配。Templates you downloaded or referenced from the GitHub Repo "azure-docs-json-samples" must be modified in order to match the Azure China Cloud Environment. 例如,替换某些终结点(将“blob.core.windows.net”替换为“blob.core.chinacloudapi.cn”,将“cloudapp.azure.com”替换为“chinacloudapp.cn”);必要时更改某些不受支持的位置、VM 映像、VM 大小、SKU 以及资源提供程序的 API 版本。For example, replace some endpoints -- "blob.core.windows.net" by "blob.core.chinacloudapi.cn", "cloudapp.azure.com" by "chinacloudapp.cn"; change some unsupported Location, VM images, VM sizes, SKU and resource-provider's API Version when necessary.

    3. 选择“文件” > “另存为”,使用名称“CreateKeyVault.json”将该文件的副本保存到本地计算机。 Select File > Save As, and then save a copy of the file to your local computer with the name CreateKeyVault.json.

  2. 在本地计算机上运行以下 Azure PowerShell 脚本。Run the following Azure PowerShell script on you local computer.

    # Sign in the Azure China Cloud
    Connect-AzAccount -Environment AzureChinaCloud
    
    $projectName = Read-Host -Prompt "Enter a project name that is used for generating resource names"
    $location = Read-Host -Prompt "Enter the location (i.e. chinaeast)"
    $upn = Read-Host -Prompt "Enter your user principal name (email address) used to sign in to Azure"
    $secretValue = Read-Host -Prompt "Enter the virtual machine administrator password" -AsSecureString
    
    $resourceGroupName = "${projectName}rg"
    $keyVaultName = $projectName
    $adUserId = (Get-AzADUser -UserPrincipalName $upn).Id
    $templateFile = "CreateKeyVault.json"
    
    New-AzResourceGroup -Name $resourceGroupName -Location $location
    New-AzResourceGroupDeployment -ResourceGroupName $resourceGroupName -TemplateFile $templateFile -keyVaultName $keyVaultName -adUserId $adUserId -secretValue $secretValue
    
    Write-Host "Press [ENTER] to continue ..."
    

    重要

    • 资源组名称是追加了“rg”的项目名称。The resource group name is the project name, but with rg appended to it. 为了方便清理本教程创建的资源,请在部署下一模板时使用相同的项目名称和资源组名称。To make it easier to clean up the resources that you created in this tutorial, use the same project name and resource group name when you deploy the next template.
    • 密钥的默认名称为 vmAdminPassword。The default name for the secret is vmAdminPassword. 该名称已在模板中硬编码。It's hardcoded in the template.
    • 要使模板能够检索机密,必须为密钥保管库启用名为“启用对 Azure 资源管理器的访问以部署模板”的访问策略。To enable the template to retrieve the secret, you must enable an access policy called Enable access to Azure Resource Manager for template deployment for the key vault. 在模板中启用此策略。This policy is enabled in the template. 有关此访问策略的详细信息,请参阅部署密钥保管库和机密For more information about the access policy, see Deploy key vaults and secrets.

模板有一个名为 keyVaultId 的输出值。The template has one output value, called keyVaultId. 在本教程中稍后将使用此 ID 和机密名称来检索机密值。You will use this ID along with the secret name to retrieve the secret value later in the tutorial. 资源 ID 格式为:The resource ID format is:

/subscriptions/<SubscriptionID>/resourceGroups/mykeyvaultdeploymentrg/providers/Microsoft.KeyVault/vaults/<KeyVaultName>

复制并粘贴 ID 时,此 ID 可能会拆分成多个行。When you copy and paste the ID, it might be broken into multiple lines. 合并这些行并裁剪掉额外的空格。Merge the lines and trim the extra spaces.

若要对部署进行验证,请在同一 shell 窗格中运行以下 PowerShell 命令,以明文形式检索机密。To validate the deployment, run the following PowerShell command in the same shell pane to retrieve the secret in clear text. 此命令只能在同一 shell 会话中使用,因为它使用在先前 PowerShell 脚本中定义的变量 $keyVaultName。The command works only in the same shell session, because it uses the variable $keyVaultName, which is defined in the preceding PowerShell script.

(Get-AzKeyVaultSecret -vaultName $keyVaultName  -name "vmAdminPassword").SecretValueText

现在已准备好密钥保管库和密钥。Now you've prepared a key vault and a secret. 以下部分显示如何自定义现有模板,以便在部署过程中检索机密。The following sections show you how to customize an existing template to retrieve the secret during the deployment.

打开快速入门模板Open a quickstart template

Azure 快速入门模板是 ARM 模板的存储库。Azure Quickstart Templates is a repository for ARM templates. 无需从头开始创建模板,只需找到一个示例模板并对其自定义即可。Instead of creating a template from scratch, you can find a sample template and customize it. 本教程中使用的模板称为部署简单的 Windows VMThe template that's used in this tutorial is called Deploy a simple Windows VM.

  1. 在 Visual Studio Code 中,选择“文件” > “打开文件”。 In Visual Studio Code, select File > Open File.

  2. 在“文件名”框中粘贴以下 URL:In the File name box, paste the following URL:

    https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/101-vm-simple-windows/azuredeploy.json
    
  3. 选择“打开”以打开该文件。Select Open to open the file. 方案与以下教程中使用的方案相同:创建包含依赖资源的 ARM 模板The scenario is the same as the one that's used in Tutorial: Create ARM templates with dependent resources. 该模板定义了六个资源:The template defines six resources:

    • Microsoft.Storage/storageAccounts.Microsoft.Storage/storageAccounts.

    • Microsoft.Network/publicIPAddresses.Microsoft.Network/publicIPAddresses.

    • Microsoft.Network/networkSecurityGroups.Microsoft.Network/networkSecurityGroups.

    • Microsoft.Network/virtualNetworks.Microsoft.Network/virtualNetworks.

    • Microsoft.Network/networkInterfaces.Microsoft.Network/networkInterfaces.

    • Microsoft.Compute/virtualMachines.Microsoft.Compute/virtualMachines.

    在自定义模板之前,不妨对其进行一些基本的了解。It's helpful to have some basic understanding of the template before you customize it.

  4. 选择“文件” > “另存为”,将该文件的副本保存到名为 azuredeploy.json 的本地计算机。 Select File > Save As, and then save a copy of the file to your local computer with the name azuredeploy.json.

  5. 重复步骤 1-3 打开以下 URL,然后将文件保存为 azuredeploy.parameters.json。Repeat steps 1-3 to open the following URL, and then save the file as azuredeploy.parameters.json.

    https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/101-vm-simple-windows/azuredeploy.parameters.json
    

编辑参数文件Edit the parameters file

通过使用静态 ID 方法,无需对模板文件进行任何更改。By using the static ID method, you don't need to make any changes to the template file. 通过配置模板参数文件来检索机密值。Retrieving the secret value is done by configuring the template parameter file.

  1. 在 Visual Studio Code 中打开 azuredeploy.parameters.json(如果尚未打开)。In Visual Studio Code, open azuredeploy.parameters.json if it's not already open.

  2. adminPassword 参数更新为:Update the adminPassword parameter to:

    "adminPassword": {
        "reference": {
            "keyVault": {
            "id": "/subscriptions/<SubscriptionID>/resourceGroups/mykeyvaultdeploymentrg/providers/Microsoft.KeyVault/vaults/<KeyVaultName>"
            },
            "secretName": "vmAdminPassword"
        }
    },
    

    重要

    将“id”值替换为你在上一过程中创建的密钥保管库的资源 ID。Replace the value for id with the resource ID of the key vault that you created in the previous procedure. secretName 将硬编码为“vmAdminPassword”。The secretName is hardcoded as vmAdminPassword. 请参阅准备密钥保管库See Prepare a key vault.

    集成密钥保管库和资源管理器模板虚拟机部署参数文件

  3. 请更新以下值:Update the following values:

    • adminUsername:虚拟机管理员帐户的名称。adminUsername: The name of the virtual machine administrator account.
    • dnsLabelPrefix:为 dnsLabelPrefix 值命名。dnsLabelPrefix: Name the dnsLabelPrefix value.

    有关名称的示例,请参阅前面的图像。For examples of names, see the preceding image.

  4. 保存更改。Save the changes.

部署模板Deploy the template

  1. 运行以下 PowerShell 脚本以部署该模板。Run the following PowerShell script to deploy the template.

    $projectName = Read-Host -Prompt "Enter the same project name that is used for creating the key vault"
    $location = Read-Host -Prompt "Enter the same location that is used for creating the key vault (i.e. chinaeast)"
    $resourceGroupName = "${projectName}rg"
    
    New-AzResourceGroupDeployment `
        -ResourceGroupName $resourceGroupName `
        -TemplateFile "$HOME/azuredeploy.json" `
        -TemplateParameterFile "$HOME/azuredeploy.parameters.json"
    
    Write-Host "Press [ENTER] to continue ..."
    

    部署模板时,请使用密钥保管库中使用的同一资源组。When you deploy the template, use the same resource group that you used in the key vault. 此方法使你更轻松地清理资源,因为你需要仅删除一个资源组,而不是两个资源组。This approach makes it easier for you to clean up the resources, because you need to delete only one resource group instead of two.

验证部署Validate the deployment

成功部署虚拟机后,使用密钥保管库中存储的密码来测试登录凭据。After you've successfully deployed the virtual machine, test the sign-in credentials by using the password that's stored in the key vault.

  1. 打开 Azure 门户Open the Azure portal.

  2. 选择“资源组” > <YourResourceGroupName> > “simpleWinVM” 。Select Resource groups > <YourResourceGroupName> > simpleWinVM.

  3. 选择顶部的“连接”。Select connect at the top.

  4. 选择“下载 RDP 文件”,然后遵照说明使用密钥保管库中存储的密码登录到虚拟机。Select Download RDP File, and then follow the instructions to sign in to the virtual machine by using the password that's stored in the key vault.

清理资源Clean up resources

不再需要 Azure 资源时,请通过删除资源组来清理已部署的资源。When you no longer need your Azure resources, clean up the resources that you deployed by deleting the resource group.

$projectName = Read-Host -Prompt "Enter the same project name that is used for creating the key vault"
$resourceGroupName = "${projectName}rg"

Remove-AzResourceGroup -Name $resourceGroupName

Write-Host "Press [ENTER] to continue ..."

后续步骤Next steps

在本教程中,你已从 Azure 密钥保管库检索了一个密钥。In this tutorial, you retrieved a secret from your Azure key vault. 你然后使用模板部署中的密钥。You then used the secret in your template deployment. 若要了解如何使用虚拟机扩展执行部署后任务,请参阅:To learn how to use virtual machine extensions to perform post deployment tasks, see: