您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

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

本文介绍如何配合使用 Azure PowerShell 与资源管理器模板,以将资源部署到 Azure。This article explains how to use Azure PowerShell with Resource Manager templates to deploy your resources to Azure. 如果不熟悉部署和管理 Azure 解决方案的概念,请参阅 Azure 资源管理器概述If you are not familiar with the concepts of deploying and managing your Azure solutions, see Azure Resource Manager overview.

所部署的 Resource Manager 模板可以是计算机上的本地文件,也可以是位于 GitHub 等存储库中的外部文件。The Resource Manager template you deploy can either be a local file on your machine, or an external file that is located in a repository like GitHub. 本文中部署的模板可在示例模板部分中找到,也可作为 GitHub 中的存储帐户模板The template you deploy in this article is available in the Sample template section, or as storage account template in GitHub.

必要时,请使用 Azure PowerShell 指南中的说明安装 Azure PowerShell 模块,然后运行 Connect-AzureRmAccount 创建与 Azure 的连接。If needed, install the Azure PowerShell module using the instructions found in the Azure PowerShell guide, and then run Connect-AzureRmAccount to create a connection with Azure.

从本地计算机部署模板Deploy a template from your local machine

将资源部署到 Azure 时,执行以下操作:When deploying resources to Azure, you:

  1. 登录到 Azure 帐户Log in to your Azure account
  2. 创建用作已部署资源的容器的资源组。Create a resource group that serves as the container for the deployed resources. 资源组名称只能包含字母数字字符、句点、下划线、连字符和括号。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 cannot end in a period.
  3. 将定义了要创建的资源的模板部署到资源组Deploy to the resource group the template that defines the resources to create

模板可以包括可用于自定义部署的参数。A template can include parameters that enable you to customize the deployment. 例如,可以提供为特定环境(如开发环境、测试环境和生产环境)定制的值。For example, you can provide values that are tailored for a particular environment (such as dev, test, and production). 示例模板定义了存储帐户 SKU 的参数。The sample template defines a parameter for the storage account SKU.

以下示例将创建一个资源组,并从本地计算机部署模板:The following example creates a resource group, and deploys a template from your local machine:

Connect-AzureRmAccount

Select-AzureRmSubscription -SubscriptionName <yourSubscriptionName>

New-AzureRmResourceGroup -Name ExampleResourceGroup -Location "South Central US"
New-AzureRmResourceGroupDeployment -Name ExampleDeployment -ResourceGroupName ExampleResourceGroup `
  -TemplateFile c:\MyTemplates\storage.json -storageAccountType Standard_GRS

部署可能需要几分钟才能完成。The deployment can take a few minutes to complete. 完成后,会看到一条包含结果的消息:When it finishes, you see a message that includes the result:

ProvisioningState       : Succeeded

从外部源部署模板Deploy a template from an external source

可能更愿意将 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.

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

前面的示例要求模板的 URI 可公开访问,它适用于大多数情况,因为模板应该不会包含敏感数据。The preceding example requires a publicly accessible URI for the template, which works for most scenarios because your template should not include sensitive data. 如果需要指定敏感数据(如管理员密码),请以安全参数的形式传递该值。If you need to specify sensitive data (like an admin password), pass that value as a secure parameter. 但是,如果不希望模板可公开访问,可以通过将其存储在专用存储容器中来保护它。However, if you do not 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.

从 Cloud Shell 部署模板Deploy template from Cloud Shell

可以使用 Cloud Shell 来部署模板。You can use Cloud Shell to deploy your template. 但是,必须先将模板加载到 Cloud Shell 的存储帐户。However, you must first load your template into the storage account for your Cloud Shell. 如果尚未使用过 Cloud Shell,请参阅 Azure Cloud Shell 概述,了解如何设置它。If you have not used Cloud Shell, see Overview of Azure Cloud Shell for information about setting it up.

  1. 登录到 Azure 门户Log in to the Azure portal.

  2. 选择 Cloud Shell 资源组。Select your Cloud Shell resource group. 名称模式为 cloud-shell-storage-<region>The name pattern is cloud-shell-storage-<region>.

    选择资源组

  3. 选择适用于 Cloud Shell 的存储帐户。Select the storage account for your Cloud Shell.

    选择存储帐户

  4. 选择“Blob”。Select Blobs.

    选择 Blob

  5. 选择“+ 容器”。Select + Container.

    添加容器

  6. 为容器指定名称和访问级别。Give your container a name and an access level. 本文中的示例模板未包含任何敏感信息,因此允许进行匿名读取访问。The sample template in this article contains no sensitive information, so allow anonymous read access. 选择“确定”。Select OK.

    提供容器值

  7. 选择你创建的容器。Select the container you created.

    选择新容器

  8. 选择“上传”。Select Upload.

    上传 blob

  9. 找到并上传模板。Find and upload your template.

    上传文件

  10. 在它上传后,选择模板。After it has uploaded, select the template.

    选择新模板

  11. 复制 URL。Copy the URL.

    复制 URL

  12. 打开提示符。Open the prompt.

    打开 Cloud Shell

在 Cloud Shell 中使用以下命令:In the Cloud Shell, use the following commands:

New-AzureRmResourceGroup -Name ExampleResourceGroup -Location "South Central US"
New-AzureRmResourceGroupDeployment -ResourceGroupName ExampleResourceGroup `
  -TemplateUri <copied URL> `
  -storageAccountType Standard_GRS

部署到多个资源组或订阅Deploy to more than one resource group or subscription

通常情况下,将模板中的所有资源部署到单个资源组。Typically, you deploy all the resources in your template to a single resource group. 不过,在某些情况下,你可能希望将一组资源部署在一起但将其放置在不同的资源组或订阅中。However, there are scenarios where you want to deploy a set of resources together but place them in different resource groups or subscriptions. 在单个部署中可以仅部署到五个资源组。You can deploy to only five resource groups in a single deployment. 有关详细信息,将 Azure 资源部署到多个订阅或资源组For more information, see Deploy Azure resources to more than one subscription or resource group.

参数文件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. 参数文件必须采用以下格式: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 multiple parameter files for different deployment scenarios, and then pass in the appropriate parameter file.

复制上面的示例,并将其保存为名为 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-AzureRmResourceGroupDeployment -Name ExampleDeployment -ResourceGroupName ExampleResourceGroup `
  -TemplateFile c:\MyTemplates\storage.json `
  -TemplateParameterFile c:\MyTemplates\storage.parameters.json

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

New-AzureRmResourceGroupDeployment -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

可以在同一部署操作中使用内联参数和本地参数文件。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 cannot 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 cannot include in the parameter file, either add that value to a key vault, or dynamically provide all parameter values inline.

如果模板包括的一个参数与 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-AzureRmResourceGroupDeployment cmdlet 中的 ResourceGroupName 参数冲突。For example, a parameter named ResourceGroupName in your template conflicts with the ResourceGroupName parameter in the New-AzureRmResourceGroupDeployment cmdlet. 系统会提示提供 ResourceGroupNameFromTemplate 的值。You are 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 a template deployment

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

Test-AzureRmResourceGroupDeployment -ResourceGroupName ExampleResourceGroup `
  -TemplateFile c:\MyTemplates\storage.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, attempting to pass an incorrect value for the storage account SKU, returns the following error:

Test-AzureRmResourceGroupDeployment -ResourceGroupName testgroup `
  -TemplateFile c:\MyTemplates\storage.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 could not parse the template. 该消息会指出分析错误的行号和位置。The message indicates the line number and position of the parsing error.

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

增量部署和完整部署Incremental and complete deployments

部署资源时,可以指定部署为增量更新还是完整更新。When deploying your resources, you specify that the deployment is either an incremental update or a complete update. 这两种模式的主要区别是 Resource Manager 如何处理资源组中不在模板中的现有资源:The primary difference between these two modes is how Resource Manager handles existing resources in the resource group that are not in the template:

  • 在完整模式中,Resource Manager 删除资源组中已存在但尚未在模板中指定的资源。In complete mode, Resource Manager deletes resources that exist in the resource group but are not specified in the template.
  • 在增量模式中,Resource Manager 保留资源组中已存在但尚未在模板中指定的资源。In incremental mode, Resource Manager leaves unchanged resources that exist in the resource group but are not specified in the template.

对于这两种模式,Resource Manager 都会尝试预配在模板中指定的所有资源。For both modes, Resource Manager attempts to provision all resources specified in the template. 如果资源已存在于资源组中且其设置未更改,该操作不会导致任何更改。If the resource already exists in the resource group and its settings are unchanged, the operation results in no change. 如果更改某个资源的设置,则会使用这些新设置预配资源。If you change the settings for a resource, the resource is provisioned with those new settings. 如果尝试更新现有资源的位置或类型,则部署会失败并出现错误。If you attempt to update the location or type of an existing resource, the deployment fails with an error. 请改用所需的位置或类型部署新资源。Instead, deploy a new resource with the location or type that you need.

Resource Manager 默认使用增量模式。By default, Resource Manager uses the incremental mode.

为了说明增量模式和完整模式的差异,请考虑以下方案。To illustrate the difference between incremental and complete modes, consider the following scenario.

现有资源组包含:Existing Resource Group contains:

  • 资源 AResource A
  • 资源 BResource B
  • 资源 CResource C

模板定义:Template defines:

  • 资源 AResource A
  • 资源 BResource B
  • 资源 DResource D

在“增量”模式下部署时,资源组包含:When deployed in incremental mode, the resource group contains:

  • 资源 AResource A
  • 资源 BResource B
  • 资源 CResource C
  • 资源 DResource D

在“完整”模式下部署时,会删除资源 C。When deployed in complete mode, Resource C is deleted. 该资源组包含:The resource group contains:

  • 资源 AResource A
  • 资源 BResource B
  • 资源 DResource D

若要使用完整模式,请使用 Mode 参数:To use complete mode, use the Mode parameter:

New-AzureRmResourceGroupDeployment -Mode Complete -Name ExampleDeployment `
  -ResourceGroupName ExampleResourceGroup -TemplateFile c:\MyTemplates\storage.json 

示例模板Sample template

本文中的示例使用以下模板。The following template is used for the examples in this article. 复制并将其另存为名为 storage.json 的文件。Copy and save it as a file named storage.json. 要了解如何创建此模板,请参阅创建第一个 Azure 资源管理器模板To understand how to create this template, see Create your first Azure Resource Manager template.

{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "storageAccountType": {
      "type": "string",
      "defaultValue": "Standard_LRS",
      "allowedValues": [
        "Standard_LRS",
        "Standard_GRS",
        "Standard_ZRS",
        "Premium_LRS"
      ],
      "metadata": {
        "description": "Storage Account type"
      }
    }
  },
  "variables": {
    "storageAccountName": "[concat(uniquestring(resourceGroup().id), 'standardsa')]"
  },
  "resources": [
    {
      "type": "Microsoft.Storage/storageAccounts",
      "name": "[variables('storageAccountName')]",
      "apiVersion": "2016-01-01",
      "location": "[resourceGroup().location]",
      "sku": {
          "name": "[parameters('storageAccountType')]"
      },
      "kind": "Storage", 
      "properties": {
      }
    }
  ],
  "outputs": {
      "storageAccountName": {
          "type": "string",
          "value": "[variables('storageAccountName')]"
      }
  }
}

后续步骤Next steps