教程:创建 Azure 资源管理器链接模板Tutorial: Create linked Azure Resource Manager templates

了解如何创建 Azure 资源管理器链接模板。Learn how to create linked Azure Resource Manager templates. 使用链接模板时,可以通过一个模板调用另一个模板。Using linked templates, you can have one template call another template. 它非常适用于模板的模块化。It is great for modularizing templates. 在本教程中使用的模板与在教程:使用依赖资源创建 Azure 资源管理器模板中使用的模板相同,该模板用于创建虚拟机、虚拟网络以及其他依赖资源(包括存储帐户)。In this tutorial, you use the same template used in Tutorial: Create Azure Resource Manager templates with dependent resources, which creates a virtual machine, a virtual network, and other dependent resource including a storage account. 请将存储帐户资源创建功能分隔到链接的模板。You separate the storage account resource creation to a linked template.

调用链接的模板就像执行函数调用一样。Calling a linked template is like making a function call. 你还将了解如何将参数值传递给链接的模板,以及如何从链接的模板中获取“返回值”。You also learn how to pass parameter values to the linked template, and how to get "return values" from the linked template.

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

  • 打开快速入门模板Open a QuickStart template
  • 创建链接模板Create the linked template
  • 上传链接模板Upload the linked template
  • 链接到链接模板Link to the linked template
  • 配置依赖项Configure dependency
  • 部署模板Deploy the template
  • 其他做法Additional practices

有关详细信息,请参阅部署 Azure 资源时使用链接的和嵌套的模板For more information, see Use linked and nested templates when deploying Azure resources.

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

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.

先决条件Prerequisites

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

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

Azure 快速入门模板是资源管理器模板的存储库。Azure QuickStart Templates is a repository for Resource Manager templates. 无需从头开始创建模板,只需找到一个示例模板并对其自定义即可。Instead of creating a template from scratch, you can find a sample template and customize it. 本教程中使用的模板称为部署简单的 Windows VMThe template used in this tutorial is called Deploy a simple Windows VM. 这是在教程:使用依赖的资源创建 Azure 资源管理器模板中使用的同一模板。This is the same template used in Tutorial: Create Azure Resource Manager templates with dependent resources. 请保存同一模板的两个副本,用作:You save two copies of the same template to be used as:

  • 主模板:创建除存储帐户之外的所有资源。The main template: create all the resources except the storage account.
  • 链接模板:创建存储帐户。The linked template: create the storage account.
  1. 在 Visual Studio Code 中,选择“文件”>“打开文件”。From Visual Studio Code, select File>Open File.

  2. 在“文件名”中粘贴以下 URL:In File name, 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.

  4. 有五个通过此模板定义的资源:There are five resources defined by the template:

    • Microsoft.Storage/storageAccountsMicrosoft.Storage/storageAccounts.
    • Microsoft.Network/publicIPAddressesMicrosoft.Network/publicIPAddresses.
    • Microsoft.Network/virtualNetworksMicrosoft.Network/virtualNetworks.
    • Microsoft.Network/networkInterfacesMicrosoft.Network/networkInterfaces.
    • Microsoft.Compute/virtualMachinesMicrosoft.Compute/virtualMachines.

    在自定义模板之前,不妨对其进行一些基本的了解。It is helpful to get some basic understanding of the template before customizing the template.

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

  6. 选择“文件”>“另存为”,创建名为 linkedTemplate.json 的另一文件副本。Select File>Save As to create another copy of the file with the name linkedTemplate.json.

创建链接模板Create the linked template

链接模板可创建存储帐户。The linked template creates a storage account. 链接的模板可以用作独立模板来创建存储帐户。The linked template can be used as a standalone template to create a storage account. 在本教程中,链接的模板采用两个参数,并将值传递给主模板。In this tutorial, the linked template takes two parameters, and passes a value back to the main template. 此“返回”值在 outputs 元素中定义。This "return" value is defined in the outputs element.

  1. 在 Visual Studio Code 中打开 linkedTemplate.json(如果此文件尚未打开)。Open linkedTemplate.json in Visual Studio Code if the file is not opened.

  2. 进行以下更改:Make the following changes:

    • 删除除 location 之外的所有参数。Remove all the parameters other than location.

    • 添加名为 storageAccountName 的参数。Add a parameter called storageAccountName.

      "storageAccountName":{
        "type": "string",
        "metadata": {
            "description": "Azure Storage account name."
        }
      },
      

      存储帐户名称和位置作为参数从主模板传递给链接的模板。The storage account name and location are passed from the main template to the linked template as parameters.

    • 删除 variables 元素以及所有变量定义。Remove the variables element, and all the variable definitions.

    • 删除除存储帐户之外的所有资源。Remove all the resources other than the storage account. 删除总共四项资源。You remove a total of four resources.

    • 将存储帐户资源的 name 元素的值更新为:Update the value of the name element of the storage account resource to:

        "name": "[parameters('storageAccountName')]",
      
    • 更新 outputs 元素,使之如下所示:Update the outputs element, so it looks like:

      "outputs": {
        "storageUri": {
            "type": "string",
            "value": "[reference(parameters('storageAccountName')).primaryEndpoints.blob]"
          }
      }
      

      storageUri 在主模板中是虚拟机资源定义所需要的。storageUri is required by the virtual machine resource definition in the main template. 请将值作为输出值传回主模板。You pass the value back to the main template as an output value.

      完成后,模板应如下所示:When you are done, the template shall look like:

      {
        "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
        "contentVersion": "1.0.0.0",
        "parameters": {
          "storageAccountName": {
            "type": "string",
            "metadata": {
              "description": "Azure Storage account name."
            }
          },
          "location": {
            "type": "string",
            "defaultValue": "[resourceGroup().location]",
            "metadata": {
              "description": "Location for all resources."
            }
          }
        },
        "resources": [
          {
            "type": "Microsoft.Storage/storageAccounts",
            "name": "[parameters('storageAccountName')]",
            "location": "[parameters('location')]",
            "apiVersion": "2018-07-01",
            "sku": {
              "name": "Standard_LRS"
            },
            "kind": "Storage",
            "properties": {}
          }
        ],
        "outputs": {
          "storageUri": {
            "type": "string",
            "value": "[reference(parameters('storageAccountName')).primaryEndpoints.blob]"
          }
        }
      }
      
  3. 保存更改。Save the changes.

上传链接模板Upload the linked template

主模板和链接的模板必须能够从运行部署时所在的位置进行访问。The main template and the linked template need to be accessible from where you run the deployment. 在本教程中使用的本地 Shell 部署方法就是在教程:使用依赖的资源创建 Azure 资源管理器模板中使用的。In this tutorial, you use the local shell deployment method as you used in Tutorial: Create Azure Resource Manager templates with dependent resources. 主模板 (azuredeploy.json) 保存到本地电脑。The main template (azuredeploy.json) is saved on your local PC . 链接的模板 (linkedTemplate.json) 必须在某个位置安全地共享。The linked template (linkedTemplate.json) must be shared somewhere securely. 以下 PowerShell 脚本创建一个 Azure 存储帐户,然后生成一个 SAS 令牌,以便授予对模板文件的受限访问权限。The following PowerShell script creates an Azure Storage account, and then generates a SAS token to grant limited access to the template file. 为了简化本教程,该脚本会从共享位置下载一个完成的链接模板。To simplify the tutorial, the script downloads a completed linked template from a shared location.

Note

脚本将 SAS 令牌限制为在八小时内使用。The script limits the SAS token to be used within eight hours. 如果需要更多时间来完成本教程,请将到期时间推后。If you need more time to complete this tutorial, increase the expiry time.

$projectNamePrefix = Read-Host -Prompt "Enter a project name:"   # This name is used to generate names for Azure resources, such as storage account name.
$location = Read-Host -Prompt "Enter a location (i.e. chinaeast)"

$resourceGroupName = $projectNamePrefix + "rg"
$storageAccountName = $projectNamePrefix + "store"
$containerName = "linkedtemplates" # The name of the Blob container to be created.

$linkedTemplateURL = "https://armtutorials.blob.core.windows.net/linkedtemplates/linkedStorageAccount.json" # A completed linked template used in this tutorial.
$fileName = "linkedStorageAccount.json" # A file name used for downloading and uploading the linked template.

# Download the tutorial linked template
Invoke-WebRequest -Uri $linkedTemplateURL -OutFile "$home/$fileName"

# Create a resource group
New-AzResourceGroup -Name $resourceGroupName -Location $location

# Create a storage account
$storageAccount = New-AzStorageAccount `
    -ResourceGroupName $resourceGroupName `
    -Name $storageAccountName `
    -Location $location `
    -SkuName "Standard_LRS"

$context = $storageAccount.Context

# Create a container
New-AzStorageContainer -Name $containerName -Context $context

# Upload the linked template
Set-AzStorageBlobContent `
    -Container $containerName `
    -File "$home/$fileName" `
    -Blob $fileName `
    -Context $context

# Generate a SAS token
$templateURI = New-AzStorageBlobSASToken `
    -Context $context `
    -Container $containerName `
    -Blob $fileName `
    -Permission r `
    -ExpiryTime (Get-Date).AddHours(8.0) `
    -FullUri

echo "You need the following values later in the tutorial:"
echo "Resource Group Name: $resourceGroupName"
echo "Linked template URI with SAS token: $templateURI"

在实践中,请在部署主模板时生成一个 SAS 令牌,让该 SAS 令牌在更短的时间范围内到期,以增强安全性。In practice, you generate a SAS token when you deploy the main template, and give the SAS token expiry a smaller window to make it more secure. 有关详细信息,请参阅在部署期间提供 SAS 令牌For more information, see Provide SAS token during deployment.

调用链接模板Call the linked template

主模板称为 azuredeploy.json。The main template is called azuredeploy.json.

  1. 在 Visual Studio Code 中打开 azuredeploy.json(如果尚未打开)。Open azuredeploy.json in Visual Studio Code if it is not opened.

  2. 从模板中删除存储帐户资源定义:Delete the storage account resource definition from the template:

    {
      "type": "Microsoft.Storage/storageAccounts",
      "name": "[variables('storageAccountName')]",
      "location": "[parameters('location')]",
      "apiVersion": "2018-07-01",
      "sku": {
        "name": "Standard_LRS"
      },
      "kind": "Storage",
      "properties": {}
    },
    
  3. 将以下 json 代码片段添加到存储帐户定义所在的位置:Add the following json snippet to the place where you had the storage account definition:

    {
      "name": "linkedTemplate",
      "type": "Microsoft.Resources/deployments",
      "apiVersion": "2018-05-01",
      "properties": {
          "mode": "Incremental",
          "templateLink": {
              "uri":"https://armtutorials.blob.core.windows.net/linkedtemplates/linkedStorageAccount.json"
          },
          "parameters": {
              "storageAccountName":{"value": "[variables('storageAccountName')]"},
              "location":{"value": "[parameters('location')]"}
          }
      }
    },
    

    请注意以下详细信息:Pay attention to these details:

    • 主模板中的 Microsoft.Resources/deployments 资源用于链接到另一模板。A Microsoft.Resources/deployments resource in the main template is used to link to another template.
    • deployments 资源的名称为 linkedTemplateThe deployments resource has a name called linkedTemplate. 该名称用于配置依赖项This name is used for configuring dependency.
    • 在调用链接模板时,只能使用增量部署模式。You can only use Incremental deployment mode when calling linked templates.
    • templateLink/uri 包含链接模板 URI。templateLink/uri contains the linked template URI. 将值更新为在上传链接模板(与 SAS 令牌配合使用的模板)时获取的 URI。Update the value to the URI you get when you upload the linked template (the one with a SAS token).
    • 请使用 parameters 将值从主模板传递到链接模板。Use parameters to pass values from the main template to the linked template.
  4. 确保已将 uri 元素的值更新为在上传链接模板(与 SAS 令牌配合使用的模板)时获取的值。Make sure you have updated the value of the uri element to the value you got when you upload the linked template (the one with a SAS token). 在实践中,需为 URI 提供一个参数。In practice, you want to supply the URI with a parameter.

  5. 保存修订的模板Save the revised template

配置依赖项Configure dependency

回想一下,在教程:使用依赖资源创建 Azure 资源管理器模板中,虚拟机资源依赖于存储帐户:Recall from Tutorial: Create Azure Resource Manager templates with dependent resources, the virtual machine resource depends on the storage account:

Azure 资源管理器模板依赖项图

由于存储帐户现在已在链接模板中定义,因此必须更新 Microsoft.Compute/virtualMachines 资源的下述两个元素。Because the storage account is defined in the linked template now, you must update the following two elements of the Microsoft.Compute/virtualMachines resource.

  • 重新配置 dependOn 元素。Reconfigure the dependOn element. 存储帐户定义移到链接模板。The storage account definition is moved to the linked template.

  • 重新配置 properties/diagnosticsProfile/bootDiagnostics/storageUri 元素。Reconfigure the properties/diagnosticsProfile/bootDiagnostics/storageUri element. 创建链接模板中,已添加输出值:In Create the linked template, you added an output value:

    "outputs": {
        "storageUri": {
            "type": "string",
            "value": "[reference(parameters('storageAccountName')).primaryEndpoints.blob]"
            }
    }
    

    该值是主模板需要的。This value is required by the main template.

  1. 在 Visual Studio Code 中打开 azuredeploy.json(如果尚未打开)。Open azuredeploy.json in Visual Studio Code if it is not opened.

  2. 扩展虚拟机资源定义,更新 dependsOn,如以下屏幕截图所示:Expand the virtual machine resource definition, update dependsOn as shown in the following screenshot:

    Azure 资源管理器链接模板可配置依赖项Azure Resource Manager linked templates configure dependency

    linkedTemplate 是部署资源的名称。linkedTemplate is the name of the deployments resource.

  3. 更新 properties/diagnosticsProfile/bootDiagnostics/storageUri,如上一屏幕截图所示。Update properties/diagnosticsProfile/bootDiagnostics/storageUri as shown in the previous screenshot.

  4. 保存修订的模板。Save the revised template.

部署模板Deploy the template

有关部署过程,请参阅部署模板部分。Refer to the Deploy the template section for the deployment procedure. 使用与存储帐户相同的资源组名称来存储链接模板。Use the same resource group name as the storage account for storing the linked template. 这样可以更方便地在下一部分清理资源。It makes it easier to clean up resources in the next section. 若要提高安全性,请使用为虚拟机管理员帐户生成的密码。To increase security, use a generated password for the virtual machine administrator account. 请参阅先决条件See Prerequisites.

清理资源Clean up resources

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

  1. 在 Azure 门户上的左侧菜单中选择“资源组”。From the Azure portal, select Resource group from the left menu.
  2. 在“按名称筛选”字段中输入资源组名称。Enter the resource group name in the Filter by name field.
  3. 选择资源组名称。Select the resource group name. 应会看到,该资源组中总共有六个资源。You shall see a total of six resources in the resource group.
  4. 在顶部菜单中选择“删除资源组”。Select Delete resource group from the top menu.

其他做法Additional practice

若要改进项目,请对已完成的项目进行下述其他更改:To improve the project, make the following additional changes to the completed project:

  1. 修改主模板 (azuredeploy.json),使之通过参数获取链接模板 URI 值。Modify the main template (azuredeploy.json) so that it takes the linked template URI value via a parameter.
  2. 请在部署主模板时生成 SAS 令牌,而不是在上传链接模板时生成该令牌。Instead of generating a SAS token when you upload the linked template, generate the token when you deploy the main template. 有关详细信息,请参阅在部署期间提供 SAS 令牌For more information, see Provide SAS token during deployment.