使用 Resource Manager 模板和 Azure PowerShell 部署资源Deploy resources with Resource Manager templates and Azure PowerShell

了解如何将 Azure PowerShell 与 资源管理器模板配合使用,以向 Azure 部署资源。Learn how to use Azure PowerShell with Resource Manager templates to deploy your resources to Azure. 有关部署和管理 Azure 解决方案的概念的详细信息,请参阅 Azure 资源管理器概述For more information about the concepts of deploying and managing your Azure solutions, see Azure Resource Manager overview.

Note

本文进行了更新,以便使用新的 Azure PowerShell Az 模块。This article has been updated to use the new Azure PowerShell Az module. 你仍然可以使用 AzureRM 模块,至少在 2020 年 12 月之前,它将继续接收 bug 修补程序。You can still use the AzureRM module, which will continue to receive bug fixes until at least December 2020. 若要详细了解新的 Az 模块和 AzureRM 兼容性,请参阅新 Azure Powershell Az 模块简介To learn more about the new Az module and AzureRM compatibility, see Introducing the new Azure PowerShell Az module. 有关 Az 模块安装说明,请参阅安装 Azure PowerShellFor Az module installation instructions, see Install Azure PowerShell.

部署范围Deployment scope

可将部署目标设定为 Azure 订阅或订阅中的资源组。You can target your deployment to either an Azure subscription or a resource group within a subscription. 大多数情况下,我们会将以资源组指定为部署目标。In most cases, you'll target deployment to a resource group. 可以使用订阅部署在整个订阅中应用策略和角色分配。Use subscription deployments to apply policies and role assignments across the subscription. 还可以使用订阅部署创建资源组并向其部署资源。You also use subscription deployments to create a resource group and deploy resources to it. 你将根据部署范围使用不同的命令。Depending on the scope of the deployment, you use different commands.

若要部署到资源组,请使用 New-AzResourceGroupDeploymentTo deploy to a resource group, use New-AzResourceGroupDeployment:

New-AzResourceGroupDeployment -ResourceGroupName <resource-group-name> -TemplateFile <path-to-template>

若要部署到订阅,请使用 New-AzDeploymentTo deploy to a subscription, use New-AzDeployment:

New-AzDeployment -Location <location> -TemplateFile <path-to-template>

目前,仅通过 REST API 支持管理组部署。Currently, management group deployments are only supported through the REST API. 请参阅使用资源管理器模板和资源管理器 REST API 部署资源See Deploy resources with Resource Manager templates and Resource Manager REST API.

本文中的示例使用资源组部署。The examples in this article use resource group deployments. 有关订阅部署的详细信息,请参阅在订阅级别创建资源组和资源For more information about subscription deployments, see Create resource groups and resources at the subscription level.

先决条件Prerequisites

你需要使用模板进行部署。You need a template to deploy. 如果还没有模板,请从 Azure 快速入门模板存储库下载并保存一个示例模板If you don't already have one, download and save an example template from the Azure Quickstart templates repo. 本文中使用的本地文件名称为 c:\MyTemplates\azuredeploy.jsonThe local file name used in this article is c:\MyTemplates\azuredeploy.json.

需安装 Azure PowerShell 并连接到 Azure:You need to install Azure PowerShell and connect to Azure:

部署本地模板Deploy local template

以下示例将创建一个资源组,并从本地计算机部署模板。The following example creates a resource group, and deploys a template from your local machine. 资源组名称只能包含字母数字字符、句点、下划线、连字符和括号。The name of the resource group can only include alphanumeric characters, periods, underscores, hyphens, and parenthesis. 它最多可以包含 90 个字符。It can be up to 90 characters. 它不能以句点结尾。It can't end in a period.

Connect-AZAccount -Environment AzureChinaCloud
$resourceGroupName = Read-Host -Prompt "Enter the Resource Group name"
$location = Read-Host -Prompt "Enter the location (i.e. chinaeast)"

New-AzResourceGroup -Name $resourceGroupName -Location $location
New-AzResourceGroupDeployment -ResourceGroupName $resourceGroupName `
  -TemplateFile c:\MyTemplates\azuredeploy.json

部署可能需要几分钟才能完成。The deployment can take a few minutes to complete.

部署远程模板Deploy remote template

你可能更愿意将 Resource Manager 模板存储在外部位置,而不是存储在本地计算机上。Instead of storing Resource Manager templates on your local machine, you may prefer to store them in an external location. 可以将模板存储在源控件存储库(例如 GitHub)中。You can store templates in a source control repository (such as GitHub). 另外,还可以将其存储在 Azure 存储帐户中,以便在组织中共享访问。Or, you can store them in an Azure storage account for shared access in your organization.

若要部署外部模板,请使用 TemplateUri 参数。To deploy an external template, use the TemplateUri parameter. 使用示例中的 URI 从 GitHub 部署示例模板。Use the URI in the example to deploy the sample template from GitHub.

$resourceGroupName = Read-Host -Prompt "Enter the Resource Group name"
$location = Read-Host -Prompt "Enter the location (i.e. chinaeast)"

New-AzResourceGroup -Name $resourceGroupName -Location $location
New-AzResourceGroupDeployment -ResourceGroupName $resourceGroupName `
  -TemplateUri https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/101-storage-account-create/azuredeploy.json

前面的示例要求模板的 URI 可公开访问,它适用于大多数情况,因为模板应该不会包含敏感数据。The preceding example requires a publicly accessible URI for the template, which works for most scenarios because your template shouldn't include sensitive data. 如果需要指定敏感数据(如管理员密码),请以安全参数的形式传递该值。If you need to specify sensitive data (like an admin password), pass that value as a secure parameter. 但是,如果不希望模板可公开访问,可以通过将其存储在专用存储容器中来保护它。However, if you don't want your template to be publicly accessible, you can protect it by storing it in a private storage container. 若要了解如何部署需要共享访问签名 (SAS) 令牌的模板,请参阅部署具有 SAS 令牌的专用模板For information about deploying a template that requires a shared access signature (SAS) token, see Deploy private template with SAS token. 若要完成教程,请参阅教程:在资源管理器模板部署中集成 Azure Key VaultTo go through a tutorial, see Tutorial: Integrate Azure Key Vault in Resource Manager Template deployment.

部署失败时,重新部署Redeploy when deployment fails

此功能也称为“出错时回滚” 。This feature is also known as Rollback on error. 部署失败时,可以自动重新部署部署历史记录中先前成功的部署。When a deployment fails, you can automatically redeploy an earlier, successful deployment from your deployment history. 若要指定重新部署,请在部署命令中使用 -RollbackToLastDeployment-RollBackDeploymentName 参数。To specify redeployment, use either the -RollbackToLastDeployment or -RollBackDeploymentName parameter in the deployment command. 如果基础结构部署存在一个已知良好的状态,并且你希望还原到此状态,则此功能非常有用。This functionality is useful if you've got a known good state for your infrastructure deployment and want to revert to this state. 有许多需要注意的问题和限制:There are a number of caveats and restrictions:

  • 重新部署使用与以前运行它时相同的参数以相同的方式运行。The redeployment is run exactly as it was run previously with the same parameters. 无法更改参数。You can't change the parameters.
  • 以前的部署是使用完整模式运行的。The previous deployment is run using the complete mode. 以前的部署中未包括的任何资源都将被删除,任何资源配置都将设置为以前的状态。Any resources not included in the previous deployment are deleted, and any resource configurations are set to their previous state. 请确保你完全理解部署模式Make sure you fully understand the deployment modes.
  • 重新部署只会影响资源,而不会影响任何数据更改。The redeployment only affects the resources, any data changes aren't affected.
  • 只有资源组部署支持此功能,订阅级部署不支持此功能。This feature is only supported on Resource Group deployments, not subscription level deployments. 有关订阅级部署的详细信息,请参阅在订阅级别创建资源组和资源For more information about subscription level deployment, see Create resource groups and resources at the subscription level.

若要使用此选项,部署必须具有唯一的名称,以便可以在历史记录中标识它们。To use this option, your deployments must have unique names so they can be identified in the history. 如果没有唯一名称,则当前失败的部署可能会覆盖历史记录中以前成功的部署。If you don't have unique names, the current failed deployment might overwrite the previously successful deployment in the history. 只能将此选项用于根级别部署。You can only use this option with root level deployments. 从嵌套模板进行的部署不可用于重新部署。Deployments from a nested template aren't available for redeployment.

若要重新部署最后一个成功的部署,请将 -RollbackToLastDeployment 参数添加为标志。To redeploy the last successful deployment, add the -RollbackToLastDeployment parameter as a flag.

New-AzResourceGroupDeployment -Name ExampleDeployment02 `
  -ResourceGroupName $resourceGroupName `
  -TemplateFile c:\MyTemplates\azuredeploy.json `
  -RollbackToLastDeployment

若要重新部署某个特定部署,请使用 -RollBackDeploymentName 参数并提供部署名称。To redeploy a specific deployment, use the -RollBackDeploymentName parameter and provide the name of the deployment.

New-AzResourceGroupDeployment -Name ExampleDeployment02 `
  -ResourceGroupName $resourceGroupName `
  -TemplateFile c:\MyTemplates\azuredeploy.json `
  -RollBackDeploymentName ExampleDeployment01

指定的部署必须已成功。The specified deployment must have succeeded.

粘贴参数值Pass parameter values

若要传递参数值,可以使用内联参数或参数文件。To pass parameter values, you can use either inline parameters or a parameter file. 本文中前面的示例显示了内联参数。The preceding examples in this article show inline parameters.

内联参数Inline parameters

若要传递内联参数,请使用 New-AzResourceGroupDeployment 命令提供参数的名称。To pass inline parameters, provide the names of the parameter with the New-AzResourceGroupDeployment command. 例如,若要将字符串和数组传递给模板,请使用:For example, to pass a string and array to a template, use:

$arrayParam = "value1", "value2"
New-AzResourceGroupDeployment -ResourceGroupName testgroup `
  -TemplateFile c:\MyTemplates\demotemplate.json `
  -exampleString "inline string" `
  -exampleArray $arrayParam

还可以获取文件的内容并将该内容作为内联参数提供。You can also get the contents of file and provide that content as an inline parameter.

$arrayParam = "value1", "value2"
New-AzResourceGroupDeployment -ResourceGroupName testgroup `
  -TemplateFile c:\MyTemplates\demotemplate.json `
  -exampleString $(Get-Content -Path c:\MyTemplates\stringcontent.txt -Raw) `
  -exampleArray $arrayParam

当需要提供配置值时,从文件中获取参数值非常有用。Getting a parameter value from a file is helpful when you need to provide configuration values. 例如,可以为 Linux 虚拟机提供 cloud-init 值For example, you can provide cloud-init values for a Linux virtual machine.

如果需要传入对象数组,请在 PowerShell 中创建哈希表并将其添加到数组中。If you need to pass in an array of objects, create hash tables in PowerShell and add them to an array. 在部署过程中将该数组作为参数传递。Pass that array as a parameter during deployment.

$hash1 = @{ Name = "firstSubnet"; AddressPrefix = "10.0.0.0/24"}
$hash2 = @{ Name = "secondSubnet"; AddressPrefix = "10.0.1.0/24"}
$subnetArray = $hash1, $hash2
New-AzResourceGroupDeployment -ResourceGroupName testgroup `
  -TemplateFile c:\MyTemplates\demotemplate.json `
  -exampleArray $subnetArray

参数文件Parameter files

你可能会发现,与在脚本中以内联值的形式传递参数相比,使用包含参数值的 JSON 文件更为容易。Rather than passing parameters as inline values in your script, you may find it easier to use a JSON file that contains the parameter values. 参数文件可以是本地文件,也可以是具有可访问 URI 的外部文件。The parameter file can be a local file or an external file with an accessible URI.

参数文件必须采用以下格式:The parameter file must be in the following format:

{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
     "storageAccountType": {
         "value": "Standard_GRS"
     }
  }
}

请注意,parameters 部分包含与模板中定义的参数匹配的参数名称 (storageAccountType)。Notice that the parameters section includes a parameter name that matches the parameter defined in your template (storageAccountType). 参数文件包含该参数的值。The parameter file contains a value for the parameter. 此值在部署期间自动传递给模板。This value is automatically passed to the template during deployment. 可以创建多个参数文件,然后为方案传入适当的参数文件。You can create more than one parameter file, and then pass in the appropriate parameter file for the scenario.

复制上面的示例,然后将其另存为名为 storage.parameters.json 的文件。Copy the preceding example and save it as a file named storage.parameters.json.

若要传递本地参数文件,请使用 TemplateParameterFile 参数:To pass a local parameter file, use the TemplateParameterFile parameter:

New-AzResourceGroupDeployment -Name ExampleDeployment -ResourceGroupName ExampleResourceGroup `
  -TemplateFile c:\MyTemplates\azuredeploy.json `
  -TemplateParameterFile c:\MyTemplates\storage.parameters.json

若要传递外部参数文件,请使用 TemplateParameterUri 参数:To pass an external parameter file, use the TemplateParameterUri parameter:

New-AzResourceGroupDeployment -Name ExampleDeployment -ResourceGroupName ExampleResourceGroup `
  -TemplateUri https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/101-storage-account-create/azuredeploy.json `
  -TemplateParameterUri https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/101-storage-account-create/azuredeploy.parameters.json

参数优先级Parameter precedence

可以在同一部署操作中使用内联参数和本地参数文件。You can use inline parameters and a local parameter file in the same deployment operation. 例如,可以在本地参数文件中指定某些值,并在部署期间添加其他内联值。For example, you can specify some values in the local parameter file and add other values inline during deployment. 如果同时为本地参数文件中的参数和内联参数提供值,则内联值优先。If you provide values for a parameter in both the local parameter file and inline, the inline value takes precedence.

但是,使用外部参数文件时,不能传递是内联值或来自本地文件的其他值。However, when you use an external parameter file, you can't pass other values either inline or from a local file. 如果在 TemplateParameterUri 参数中指定参数文件,则忽略所有内联参数。When you specify a parameter file in the TemplateParameterUri parameter, all inline parameters are ignored. 提供外部文件中的所有参数值。Provide all parameter values in the external file. 如果模板包括参数文件中无法包括的敏感值,可将该值添加到密钥保管库,或者以内联方式动态提供所有参数值。If your template includes a sensitive value that you can't include in the parameter file, either add that value to a key vault, or dynamically provide all parameter values inline.

参数名冲突Parameter name conflicts

如果模板包括的一个参数与 PowerShell 命令中的某个参数同名,PowerShell 使用后缀 FromTemplate 显示模板的参数。If your template includes a parameter with the same name as one of the parameters in the PowerShell command, PowerShell presents the parameter from your template with the postfix FromTemplate. 例如,模板中名为 ResourceGroupName 的参数与 New-AzResourceGroupDeployment cmdlet 中的 ResourceGroupName 参数冲突。For example, a parameter named ResourceGroupName in your template conflicts with the ResourceGroupName parameter in the New-AzResourceGroupDeployment cmdlet. 系统会提示你提供 ResourceGroupNameFromTemplate 的值。You're prompted to provide a value for ResourceGroupNameFromTemplate. 通常,不应将参数命名为与用于部署操作的参数的名称相同以避免这种混乱。In general, you should avoid this confusion by not naming parameters with the same name as parameters used for deployment operations.

测试模板部署Test template deployments

若要测试模板和参数值而不实际部署任何资源,请使用 Test-AzureRmResourceGroupDeploymentTo test your template and parameter values without actually deploying any resources, use Test-AzureRmResourceGroupDeployment.

Test-AzResourceGroupDeployment -ResourceGroupName ExampleResourceGroup `
  -TemplateFile c:\MyTemplates\azuredeploy.json -storageAccountType Standard_GRS

如果没有检测到错误,该命令在没有响应的情况下完成。If no errors are detected, the command finishes without a response. 如果检测到错误,则该命令将返回一条错误消息。If an error is detected, the command returns an error message. 例如,如果为存储帐户 SKU 传递不正确的值,将返回以下错误:For example, passing an incorrect value for the storage account SKU, returns the following error:

Test-AzResourceGroupDeployment -ResourceGroupName testgroup `
  -TemplateFile c:\MyTemplates\azuredeploy.json -storageAccountType badSku

Code    : InvalidTemplate
Message : Deployment template validation failed: 'The provided value 'badSku' for the template parameter 'storageAccountType'
          at line '15' and column '24' is not valid. The parameter value is not part of the allowed value(s):
          'Standard_LRS,Standard_ZRS,Standard_GRS,Standard_RAGRS,Premium_LRS'.'.
Details :

如果模板有语法错误,该命令将返回一个错误,指示它无法分析该模板。If your template has a syntax error, the command returns an error indicating it couldn't parse the template. 该消息会指出分析错误的行号和位置。The message indicates the line number and position of the parsing error.

Test-AzResourceGroupDeployment : After parsing a value an unexpected character was encountered: 
  ". Path 'variables', line 31, position 3.

后续步骤Next steps