了解 Azure Resource Manager 模板的结构和语法Understand the structure and syntax of Azure Resource Manager templates

本文介绍 Azure 资源管理器模板的结构。This article describes the structure of an Azure Resource Manager template. 演示了模板的不同部分,以及可在相应部分使用的属性。It presents the different sections of a template and the properties that are available in those sections. 模板中包含可用于为部署构造值的 JSON 和表达式。The template consists of JSON and expressions that you can use to construct values for your deployment.

本文面向对资源管理器模板有一定了解的用户,This article is intended for users who have some familiarity with Resource Manager templates. 其中提供了有关模板结构和语法的详细信息。It provides detailed information about the structure and syntax of the template. 有关创建模板的简介,请参阅创建第一个 Azure 资源管理器模板If you want an introduction to creating a template, see Create your first Azure Resource Manager template.

模板格式Template format

使用最简单的结构时,模板有以下元素:In its simplest structure, a template has the following elements:

{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
  "contentVersion": "",
  "apiProfile": "",
  "parameters": {  },
  "variables": {  },
  "functions": [  ],
  "resources": [  ],
  "outputs": {  }
}
元素名称Element name 必须Required 说明Description
$schema$schema Yes 描述模板语言版本的 JSON 架构文件所在的位置。Location of the JSON schema file that describes the version of the template language.

对于资源组部署,请使用:https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#For resource group deployments, use: https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#

对于订阅部署,请使用:https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#For subscription deployments, use: https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#
contentVersioncontentVersion Yes 模板的版本(例如 1.0.0.0)。Version of the template (such as 1.0.0.0). 可为此元素提供任意值。You can provide any value for this element. 使用此值记录模板中的重要更改。Use this value to document significant changes in your template. 使用模板部署资源时,此值可用于确保使用正确的模板。When deploying resources using the template, this value can be used to make sure that the right template is being used.
apiProfileapiProfile No 用作资源类型 API 版本集合的 API 版本。An API version that serves as a collection of API versions for resource types. 使用此值可以避免为模板中的每个资源指定 API 版本。Use this value to avoid having to specify API versions for each resource in the template. 如果你指定 API 配置文件版本但不指定资源类型的 API 版本,则资源管理器将使用配置文件中为该资源类型定义的 API 版本。When you specify an API profile version and don't specify an API version for the resource type, Resource Manager uses the API version for that resource type that is defined in the profile.

将模板部署到不同的环境(例如 Azure Stack 和全球 Azure)时,API 配置文件属性非常有用。The API profile property is especially helpful when deploying a template to different environments, such as Azure Stack and global Azure. 使用 API 配置文件版本可确保模板自动使用两个环境均支持的版本。Use the API profile version to make sure your template automatically uses versions that are supported in both environments. 有关最新 API 配置文件版本以及配置文件中定义的资源 API 版本的列表,请参阅 API 配置文件For a list of the current API profile versions and the resources API versions defined in the profile, see API Profile.

有关详细信息,请参阅使用 API 配置文件跟踪版本For more information, see Track versions using API profiles.
参数parameters No 执行部署以自定义资源部署时提供的值。Values that are provided when deployment is executed to customize resource deployment.
variablesvariables No 在模板中用作 JSON 片段以简化模板语言表达式的值。Values that are used as JSON fragments in the template to simplify template language expressions.
functionsfunctions No 可在模板中使用的用户定义函数。User-defined functions that are available within the template.
resourcesresources Yes 已在资源组或订阅中部署/更新的资源类型。Resource types that are deployed or updated in a resource group or subscription.
outputsoutputs No 部署后返回的值。Values that are returned after deployment.

每个元素均有可设置的属性。Each element has properties you can set. 本文稍后将更详细地介绍模板的各个节。This article describes the sections of the template in greater detail.

语法Syntax

模板的基本语法为 JSON。The basic syntax of the template is JSON. 但是,可以使用表达式来扩展模板中可用的 JSON 值。However, you can use expressions to extend the JSON values available within the template. 表达式分别以方括号 [] 开头和结尾。Expressions start and end with brackets: [ and ], respectively. 部署模板时会计算表达式的值。The value of the expression is evaluated when the template is deployed. 表达式可以返回字符串、整数、布尔值、数组或对象。An expression can return a string, integer, boolean, array, or object. 以下示例演示了参数默认值中的表达式:The following example shows an expression in the default value of a parameter:

"parameters": {
  "location": {
    "type": "string",
    "defaultValue": "[resourceGroup().location]"
  }
},

在该表达式中,语法 resourceGroup() 调用资源管理器提供的、在模板中使用的某个函数。Within the expression, the syntax resourceGroup() calls one of the functions that Resource Manager provides for use within a template. 如同在 JavaScript 中一样,函数调用的格式为 functionName(arg1,arg2,arg3)Just like in JavaScript, function calls are formatted as functionName(arg1,arg2,arg3). 语法 .location 从该函数返回的对象中检索一个属性。The syntax .location retrieves one property from the object returned by that function.

模板函数及其参数不区分大小写。Template functions and their parameters are case-insensitive. 例如,资源管理器将 variables('var1')VARIABLES('VAR1') 解析为相同内容。For example, Resource Manager resolves variables('var1') and VARIABLES('VAR1') as the same. 在求值时,除非函数明确修改大小写(例如,使用 toUpper 或 toLower 进行修改),否则函数将保留大小写。When evaluated, unless the function expressly modifies case (such as toUpper or toLower), the function preserves the case. 某些资源类型可能会提出大小写要求,而不考虑函数求值方式。Certain resource types may have case requirements irrespective of how functions are evaluated.

要使用一个括号 [ 在开头括住文本字符串但不将其解释为表达式,请额外添加一个括号,使字符串以 [[ 开头。To have a literal string start with a bracket [, but not have it interpreted as an expression, add an extra bracket to start the string with [[.

若要将字符串值作为参数传递给函数,请使用单引号。To pass a string value as a parameter to a function, use single quotes.

"name": "[concat('storage', uniqueString(resourceGroup().id))]"

若要转义表达式中的双引号(例如,在模板中添加 JSON 对象),请使用反斜杠。To escape double quotes in an expression, such as adding a JSON object in the template, use the backslash.

"tags": {
    "CostCenter": "{\"Dept\":\"Finance\",\"Environment\":\"Production\"}"
},

模板表达式不能超过 24,576 个字符。A template expression can't exceed 24,576 characters.

有关模板函数的完整列表,请参阅 Azure Resource Manager 模板函数For the full list of template functions, see Azure Resource Manager template functions.

参数Parameters

在模板的 parameters 节中,可以指定在部署资源时能够输入的值。In the parameters section of the template, you specify which values you can input when deploying the resources. 提供针对特定环境(例如开发、测试和生产环境)定制的参数值可以自定义部署。These parameter values enable you to customize the deployment by providing values that are tailored for a particular environment (such as dev, test, and production). 无需在模板中提供参数,但如果没有参数,模板始终部署具有相同名称、位置和属性的相同资源。You don't have to provide parameters in your template, but without parameters your template would always deploy the same resources with the same names, locations, and properties.

一个模板中最多可以有 256 个参数。You're limited to 256 parameters in a template. 如本文中所示,可以通过使用包含多个属性的对象来减少参数的数量。You can reduce the number of parameters by using objects that contain multiple properties, as shown in this article.

可用属性Available properties

参数的可用属性为:The available properties for a parameter are:

"parameters": {
  "<parameter-name>" : {
    "type" : "<type-of-parameter-value>",
    "defaultValue": "<default-value-of-parameter>",
    "allowedValues": [ "<array-of-allowed-values>" ],
    "minValue": <minimum-value-for-int>,
    "maxValue": <maximum-value-for-int>,
    "minLength": <minimum-length-for-string-or-array>,
    "maxLength": <maximum-length-for-string-or-array-parameters>,
    "metadata": {
      "description": "<description-of-the parameter>" 
    }
  }
}
元素名称Element name 必须Required 说明Description
parameterNameparameterName Yes 参数的名称。Name of the parameter. 必须是有效的 JavaScript 标识符。Must be a valid JavaScript identifier.
typetype Yes 参数值的类型。Type of the parameter value. 允许的类型和值为 stringsecurestringintboolobjectsecureObjectarrayThe allowed types and values are string, securestring, int, bool, object, secureObject, and array.
defaultValuedefaultValue No 参数的默认值,如果没有为参数提供任何值。Default value for the parameter, if no value is provided for the parameter.
allowedValuesallowedValues No 用来确保提供正确值的参数的允许值数组。Array of allowed values for the parameter to make sure that the right value is provided.
minValueminValue No int 类型参数的最小值,此值是包容性的。The minimum value for int type parameters, this value is inclusive.
maxValuemaxValue No int 类型参数的最大值,此值是包容性的。The maximum value for int type parameters, this value is inclusive.
minLengthminLength No string、secure string 和 array 类型参数的最小长度,此值是包容性的。The minimum length for string, secure string, and array type parameters, this value is inclusive.
maxLengthmaxLength No string、secure string 和 array 类型参数的最大长度,此值是包容性的。The maximum length for string, secure string, and array type parameters, this value is inclusive.
说明description No 通过门户向用户显示的参数的说明。Description of the parameter that is displayed to users through the portal. 有关详细信息,请参阅模板中的注释For more information, see Comments in templates.

定义和使用参数Define and use a parameter

以下示例展示了一个简单的参数定义。The following example shows a simple parameter definition. 其中定义了参数的名称,并指定该参数要采用字符串值。It defines the name of the parameter, and specifies that it takes a string value. 该参数仅接受对其预期用途有意义的值。The parameter only accepts values that make sense for its intended use. 如果在部署过程未提供任何值时,则它会指定默认值。It specifies a default value when no value is provided during deployment. 最后,该参数包含其用途的说明。Finally, the parameter includes a description of its use.

"parameters": {
  "storageSKU": {
    "type": "string",
    "allowedValues": [
      "Standard_LRS",
      "Standard_ZRS",
      "Standard_GRS",
      "Standard_RAGRS",
      "Premium_LRS"
    ],
    "defaultValue": "Standard_LRS",
    "metadata": {
      "description": "The type of replication to use for the storage account."
    }
  }   
}

在模板中,可以使用以下语法引用参数值:In the template, you reference the value for the parameter with the following syntax:

"resources": [
  {
    "type": "Microsoft.Storage/storageAccounts",
    "sku": {
      "name": "[parameters('storageSKU')]"
    },
    ...
  }
]

包含参数的模板函数Template functions with parameters

为参数指定默认值时,可以使用大多数模板函数。When specifying the default value for a parameter, you can use most template functions. 可以使用另一个参数值生成默认值。You can use another parameter value to build a default value. 以下模板演示了如何在默认值中使用函数:The following template demonstrates the use of functions in the default value:

"parameters": {
  "siteName": {
    "type": "string",
    "defaultValue": "[concat('site', uniqueString(resourceGroup().id))]",
    "metadata": {
      "description": "The site name. To use the default value, do not specify a new value."
    }
  },
  "hostingPlanName": {
    "type": "string",
    "defaultValue": "[concat(parameters('siteName'),'-plan')]",
    "metadata": {
      "description": "The host name. To use the default value, do not specify a new value."
    }
  }
}

不能在 parameters 节中使用 reference 函数。You can't use the reference function in the parameters section. 参数在部署之前进行评估,因此,reference 函数无法获取资源的运行时状态。Parameters are evaluated before deployment so the reference function can't get the runtime state of a resource.

用作参数的对象Objects as parameters

将相关值作为对象传入可以更轻松地对其进行组织。It can be easier to organize related values by passing them in as an object. 此方法还可以减少模板中的参数数目。This approach also reduces the number of parameters in the template.

在模板中定义参数,并在部署过程中指定 JSON 对象,而不是单个值。Define the parameter in your template and specify a JSON object instead of a single value during deployment.

"parameters": {
  "VNetSettings": {
    "type": "object",
    "defaultValue": {
      "name": "VNet1",
      "location": "chinaeast",
      "addressPrefixes": [
        {
          "name": "firstPrefix",
          "addressPrefix": "10.0.0.0/22"
        }
      ],
      "subnets": [
        {
          "name": "firstSubnet",
          "addressPrefix": "10.0.0.0/24"
        },
        {
          "name": "secondSubnet",
          "addressPrefix": "10.0.1.0/24"
        }
      ]
    }
  }
},

然后,使用点运算符引用参数的子属性。Then, reference the subproperties of the parameter by using the dot operator.

"resources": [
  {
    "apiVersion": "2015-06-15",
    "type": "Microsoft.Network/virtualNetworks",
    "name": "[parameters('VNetSettings').name]",
    "location": "[parameters('VNetSettings').location]",
    "properties": {
      "addressSpace":{
        "addressPrefixes": [
          "[parameters('VNetSettings').addressPrefixes[0].addressPrefix]"
        ]
      },
      "subnets":[
        {
          "name":"[parameters('VNetSettings').subnets[0].name]",
          "properties": {
            "addressPrefix": "[parameters('VNetSettings').subnets[0].addressPrefix]"
          }
        },
        {
          "name":"[parameters('VNetSettings').subnets[1].name]",
          "properties": {
            "addressPrefix": "[parameters('VNetSettings').subnets[1].addressPrefix]"
          }
        }
      ]
    }
  }
]

参数示例模板Parameter example templates

以下示例模板演示了一些参数使用方案。These example templates demonstrate some scenarios for using parameters. 请部署这些模板,测试不同方案中参数的处理方式。Deploy them to test how parameters are handled in different scenarios.

模板Template 说明Description
用于默认值的参数与函数parameters with functions for default values 演示在定义参数的默认值时如何使用模板函数。Demonstrates how to use template functions when defining default values for parameters. 该模板不部署任何资源。The template doesn't deploy any resources. 它构造参数值并返回这些值。It constructs parameter values and returns those values.
参数对象parameter object 演示如何使用参数的对象。Demonstrates using an object for a parameter. 该模板不部署任何资源。The template doesn't deploy any resources. 它构造参数值并返回这些值。It constructs parameter values and returns those values.

变量Variables

在 variables 节中构造可在整个模板中使用的值。In the variables section, you construct values that can be used throughout your template. 不需要定义变量,但使用变量可以减少复杂的表达式,从而简化模板。You don't need to define variables, but they often simplify your template by reducing complex expressions.

可用定义Available definitions

以下示例演示了可用于定义变量的选项:The following example shows the available options for defining a variable:

"variables": {
  "<variable-name>": "<variable-value>",
  "<variable-name>": { 
    <variable-complex-type-value> 
  },
  "<variable-object-name>": {
    "copy": [
      {
        "name": "<name-of-array-property>",
        "count": <number-of-iterations>,
        "input": <object-or-value-to-repeat>
      }
    ]
  },
  "copy": [
    {
      "name": "<variable-array-name>",
      "count": <number-of-iterations>,
      "input": <object-or-value-to-repeat>
    }
  ]
}

有关使用 copy 为变量创建多个值的信息,请参阅变量迭代For information about using copy to create several values for a variable, see Variable iteration.

定义和使用变量Define and use a variable

以下示例显示了一个变量定义。The following example shows a variable definition. 它创建适用于存储帐户名称的字符串值。It creates a string value for a storage account name. 它使用多个模板函数来获取参数值,并将其连接到唯一字符串。It uses several template functions to get a parameter value, and concatenates it to a unique string.

"variables": {
  "storageName": "[concat(toLower(parameters('storageNamePrefix')), uniqueString(resourceGroup().id))]"
},

在定义资源时使用该变量。You use the variable when defining the resource.

"resources": [
  {
    "name": "[variables('storageName')]",
    "type": "Microsoft.Storage/storageAccounts",
    ...

配置变量Configuration variables

可以使用复杂的 JSON 类型为环境定义相关值。You can use complex JSON types to define related values for an environment.

"variables": {
  "environmentSettings": {
    "test": {
      "instanceSize": "Small",
      "instanceCount": 1
    },
    "prod": {
      "instanceSize": "Large",
      "instanceCount": 4
    }
  }
},

可以在参数中创建一个值,用于指示要使用的配置值。In parameters, you create a value that indicates which configuration values to use.

"parameters": {
  "environmentName": {
    "type": "string",
    "allowedValues": [
      "test",
      "prod"
    ]
  }
},

可以使用以下命令检索当前设置:You retrieve the current settings with:

"[variables('environmentSettings')[parameters('environmentName')].instanceSize]"

变量示例模板Variable example templates

以下示例模板演示了一些变量使用方案。These example templates demonstrate some scenarios for using variables. 请部署这些模板,测试不同方案中变量的处理方式。Deploy them to test how variables are handled in different scenarios.

模板Template 说明Description
变量定义variable definitions 演示不同类型的变量。Demonstrates the different types of variables. 该模板不部署任何资源。The template doesn't deploy any resources. 它构造变量值并返回这些值。It constructs variable values and returns those values.
配置变量configuration variable 演示如何使用变量来定义配置值。Demonstrates the use of a variable that defines configuration values. 该模板不部署任何资源。The template doesn't deploy any resources. 它构造变量值并返回这些值。It constructs variable values and returns those values.
网络安全规则参数文件network security rules and parameter file 以正确格式构造一个数组,以便向网络安全组分配安全规则。Constructs an array in the correct format for assigning security rules to a network security group.

函数Functions

在模板中,可以创建自己的函数。Within your template, you can create your own functions. 这些函数可在模板中使用。These functions are available for use in your template. 通常,定义不想要在整个模板中重复执行的复杂表达式。Typically, you define complicated expression that you don't want to repeat throughout your template. 从模板中支持的表达式和函数创建用户定义函数。You create the user-defined functions from expressions and functions that are supported in templates.

定义用户函数时,存在一些限制:When defining a user function, there are some restrictions:

  • 该函数不能访问变量。The function can't access variables.
  • 函数仅可使用函数中定义的参数。The function can only use parameters that are defined in the function. 如果在用户定义的函数中使用参数函数,则只能使用该函数的参数。When you use the parameters function within a user-defined function, you're restricted to the parameters for that function.
  • 该函数不能调用其他用户定义的函数。The function can't call other user-defined functions.
  • 该函数不能使用引用函数The function can't use the reference function.
  • 该函数的参数不能具有默认值。Parameters for the function can't have default values.

函数需要一个命名空间值以避免命名与模板函数发生冲突。Your functions require a namespace value to avoid naming conflicts with template functions. 下面的示例演示一个返回存储帐户名称的函数:The following example shows a function that returns a storage account name:

"functions": [
  {
    "namespace": "contoso",
    "members": {
      "uniqueName": {
        "parameters": [
          {
            "name": "namePrefix",
            "type": "string"
          }
        ],
        "output": {
          "type": "string",
          "value": "[concat(toLower(parameters('namePrefix')), uniqueString(resourceGroup().id))]"
        }
      }
    }
  }
],

可以使用以下代码调用该函数:You call the function with:

"resources": [
  {
    "name": "[contoso.uniqueName(parameters('storageNamePrefix'))]",
    "type": "Microsoft.Storage/storageAccounts",
    "apiVersion": "2016-01-01",
    "sku": {
      "name": "Standard_LRS"
    },
    "kind": "Storage",
    "location": "China East",
    "tags": {},
    "properties": {}
  }
]

资源Resources

在 resources 节,可以定义部署或更新的资源。In the resources section, you define the resources that are deployed or updated.

可用属性Available properties

使用以下结构定义资源:You define resources with the following structure:

"resources": [
  {
      "condition": "<true-to-deploy-this-resource>",
      "apiVersion": "<api-version-of-resource>",
      "type": "<resource-provider-namespace/resource-type-name>",
      "name": "<name-of-the-resource>",
      "location": "<location-of-resource>",
      "tags": {
          "<tag-name1>": "<tag-value1>",
          "<tag-name2>": "<tag-value2>"
      },
      "comments": "<your-reference-notes>",
      "copy": {
          "name": "<name-of-copy-loop>",
          "count": <number-of-iterations>,
          "mode": "<serial-or-parallel>",
          "batchSize": <number-to-deploy-serially>
      },
      "dependsOn": [
          "<array-of-related-resource-names>"
      ],
      "properties": {
          "<settings-for-the-resource>",
          "copy": [
              {
                  "name": ,
                  "count": ,
                  "input": {}
              }
          ]
      },
      "sku": {
          "name": "<sku-name>",
          "tier": "<sku-tier>",
          "size": "<sku-size>",
          "family": "<sku-family>",
          "capacity": <sku-capacity>
      },
      "kind": "<type-of-resource>",
      "plan": {
          "name": "<plan-name>",
          "promotionCode": "<plan-promotion-code>",
          "publisher": "<plan-publisher>",
          "product": "<plan-product>",
          "version": "<plan-version>"
      },
      "resources": [
          "<array-of-child-resources>"
      ]
  }
]
元素名称Element name 必须Required 说明Description
条件condition No 布尔值,该值指示在此部署期间是否将预配资源。Boolean value that indicates whether the resource will be provisioned during this deployment. true 时,在部署期间创建资源。When true, the resource is created during deployment. false 时,此部署将跳过资源。When false, the resource is skipped for this deployment. 请参阅条件See condition.
apiVersionapiVersion Yes 用于创建资源的 REST API 版本。Version of the REST API to use for creating the resource. 若要确定可用值,请参阅模板参考To determine available values, see template reference.
typetype Yes 资源的类型。Type of the resource. 此值是资源提供程序的命名空间和资源类型(例如 Microsoft.Storage/storageAccounts)的组合。This value is a combination of the namespace of the resource provider and the resource type (such as Microsoft.Storage/storageAccounts). 若要确定可用值,请参阅模板参考To determine available values, see template reference. 对于子资源,类型的格式取决于该资源是嵌套在父资源中,还是在父资源的外部定义。For a child resource, the format of the type depends on whether it's nested within the parent resource or defined outside of the parent resource. 请参阅子资源See child resources.
namename Yes 资源的名称。Name of the resource. 该名称必须遵循 RFC3986 中定义的 URI 构成部分限制。The name must follow URI component restrictions defined in RFC3986. 此外,向第三方公开资源名称的 Azure 服务会验证名称,以确保它不会尝试窃取另一身份。In addition, Azure services that expose the resource name to outside parties validate the name to make sure it isn't an attempt to spoof another identity. 对于子资源,名称的格式取决于该资源是嵌套在父资源中,还是在父资源的外部定义。For a child resource, the format of the name depends on whether it's nested within the parent resource or defined outside of the parent resource. 请参阅子资源See child resources.
locationlocation 多种多样Varies 提供的资源支持的地理位置。Supported geo-locations of the provided resource. 可以选择任何可用位置,但通常选取靠近用户的位置。You can select any of the available locations, but typically it makes sense to pick one that is close to your users. 通常还会将彼此交互的资源置于同一区域。Usually, it also makes sense to place resources that interact with each other in the same region. 大多数资源类型需要一个位置,但某些类型(如角色分配)不需要位置。Most resource types require a location, but some types (such as a role assignment) don't require a location.
标记tags No 与资源关联的标记。Tags that are associated with the resource. 应用可以在订阅中对资源进行逻辑组织的标记。Apply tags to logically organize resources across your subscription.
注释comments No 用于描述模板中资源的注释。Your notes for documenting the resources in your template. 有关详细信息,请参阅模板中的注释For more information, see Comments in templates.
复制copy No 如果需要多个实例,则为要创建的资源数。If more than one instance is needed, the number of resources to create. 默认模式为并行。The default mode is parallel. 若不想同时部署所有资源,请指定为串行模式。Specify serial mode when you don't want all or the resources to deploy at the same time. 有关详细信息,请参阅在 Azure 资源管理器中创建多个资源实例For more information, see Create several instances of resources in Azure Resource Manager.
dependsOndependsOn No 部署此资源之前必须部署的资源。Resources that must be deployed before this resource is deployed. Resource Manager 会评估资源之间的依赖关系,并按正确的顺序部署资源。Resource Manager evaluates the dependencies between resources and deploys them in the correct order. 如果资源互不依赖,则会并行部署资源。When resources aren't dependent on each other, they're deployed in parallel. 该值可以是资源名称或资源唯一标识符的逗号分隔列表。The value can be a comma-separated list of a resource names or resource unique identifiers. 在此模板中仅部署列出的资源。Only list resources that are deployed in this template. 未在此模板中定义的资源必须是已存在的资源。Resources that aren't defined in this template must already exist. 避免添加不必要的依赖项,因为这些依赖项可能会降低部署速度并创建循环依赖项。Avoid adding unnecessary dependencies as they can slow your deployment and create circular dependencies. 有关设置依赖项的指导,请参阅在 Azure Resource Manager 模板中定义依赖项For guidance on setting dependencies, see Defining dependencies in Azure Resource Manager templates.
propertiesproperties No 特定于资源的配置设置。Resource-specific configuration settings. properties 的值与创建资源时,在 REST API 操作(PUT 方法)的请求正文中提供的值相同。The values for the properties are the same as the values you provide in the request body for the REST API operation (PUT method) to create the resource. 还可以指定副本数组,为一个属性创建多个实例。You can also specify a copy array to create several instances of a property. 若要确定可用值,请参阅模板参考To determine available values, see template reference.
skusku No 某些资源接受定义了要部署的 SKU 的值。Some resources allow values that define the SKU to deploy. 例如,可以为存储帐户指定冗余类型。For example, you can specify the type of redundancy for a storage account.
kindkind No 某些资源接受定义了你部署的资源类型的值。Some resources allow a value that defines the type of resource you deploy. 例如,可以指定要创建的 Cosmos DB 的类型。For example, you can specify the type of Cosmos DB to create.
计划plan No 某些资源接受定义了要部署的计划的值。Some resources allow values that define the plan to deploy. 例如,可以为虚拟机指定市场映像。For example, you can specify the marketplace image for a virtual machine.
资源resources No 依赖于所定义的资源的子资源。Child resources that depend on the resource being defined. 只能提供父资源的架构允许的资源类型。Only provide resource types that are permitted by the schema of the parent resource. 不隐式表示对父资源的依赖。Dependency on the parent resource isn't implied. 必须显式定义该依赖关系。You must explicitly define that dependency. 请参阅子资源See child resources.

条件Condition

如果必须在部署期间决定是否创建资源,请使用 condition 元素。When you must decide during deployment whether to create a resource, use the condition element. 此元素的值将解析为 true 或 false。The value for this element resolves to true or false. 如果值为 true,则创建了该资源。When the value is true, the resource is created. 如果值为 false,则未创建该资源。When the value is false, the resource isn't created. 值只能应用到整个资源。The value can only be applied to the whole resource.

通常,当要创建新资源或使用现有资源时,可以使用此值。Typically, you use this value when you want to create a new resource or use an existing one. 例如,若要指定是要部署新的存储帐户还是使用现有存储帐户,请使用:For example, to specify whether a new storage account is deployed or an existing storage account is used, use:

{
    "condition": "[equals(parameters('newOrExisting'),'new')]",
    "type": "Microsoft.Storage/storageAccounts",
    "name": "[variables('storageAccountName')]",
    "apiVersion": "2017-06-01",
    "location": "[resourceGroup().location]",
    "sku": {
        "name": "[variables('storageAccountType')]"
    },
    "kind": "Storage",
    "properties": {}
}

有关使用 condition 元素的完整示例模板,请参阅具有新的或现有虚拟网络、存储和公共 IP 的 VMFor a complete example template that uses the condition element, see VM with a new or existing Virtual Network, Storage, and Public IP.

如果对条件性部署的资源使用 referencelist 函数,则会对该函数进行评估,即使资源尚未部署。If you use a reference or list function with a resource that is conditionally deployed, the function is evaluated even if the resource isn't deployed. 如果该函数引用某个不存在的资源,则会出现错误。You get an error if the function refers to a resource that doesn't exist. 请使用 if 函数,以确保仅当资源已部署时,才根据条件评估函数。Use the if function to make sure the function is only evaluated for conditions when the resource is deployed. 请查看示例模板的 if 函数,该模板将 if 和 reference 用于进行条件部署的资源。See the if function for a sample template that uses if and reference with a conditionally deployed resource.

资源名称Resource names

通常,会在 Resource Manager 中使用三种类型的资源名称:Generally, you work with three types of resource names in Resource Manager:

  • 必须唯一的资源名称。Resource names that must be unique.
  • 不一定是唯一的资源名称,不过,可以选择提供可帮助识别资源的名称。Resource names that aren't required to be unique, but you choose to provide a name that can help you identify the resource.
  • 通用的资源名称。Resource names that can be generic.

对于具有数据访问终结点的任何资源类型,请提供唯一的资源名称Provide a unique resource name for any resource type that has a data access endpoint. 需要唯一名称的一些常见资源类型包括:Some common resource types that require a unique name include:

  • Azure 存储1Azure Storage1
  • Azure 应用服务的 Web 应用功能Web Apps feature of Azure App Service
  • SQL ServerSQL Server
  • Azure Key VaultAzure Key Vault
  • 用于 Redis 的 Azure 缓存Azure Cache for Redis
  • Azure BatchAzure Batch
  • Azure 流量管理器Azure Traffic Manager
  • Azure 搜索Azure Search
  • Azure HDInsightAzure HDInsight

1 存储帐户名必须使用小写字母,包含 24 个或更少的字符,并且不包含任何连字符。1 Storage account names also must be lowercase, 24 characters or less, and not have any hyphens.

设置名称时,可以手动创建一个唯一的名称,也可以使用 uniqueString() 函数生成一个名称。When setting the name, you can either manually create a unique name or use the uniqueString() function to generate a name. 可能还需要在 uniqueString 结果中添加一个前缀或后缀。You also might want to add a prefix or suffix to the uniqueString result. 修改唯一的名称可以更方便地通过名称识别资源类型。Modifying the unique name can help you more easily identify the resource type from the name. 例如,可以使用以下变量生成存储帐户的唯一名称:For example, you can generate a unique name for a storage account by using the following variable:

"variables": {
  "storageAccountName": "[concat(uniqueString(resourceGroup().id),'storage')]"
}

对于某些资源类型,可能需要提供标识名称,但该名称并非一定是唯一的。For some resource types, you might want to provide a name for identification, but the name doesn't have to be unique. 对于这些资源类型,请提供一个可以描述其用途或特征的名称。For these resource types, provide a name that describes it use or characteristics.

"parameters": {
  "vmName": { 
    "type": "string",
    "defaultValue": "demoLinuxVM",
    "metadata": {
      "description": "The name of the VM to create."
    }
  }
}

对于主要通过其他资源访问的资源类型,可以在模板中使用硬编码的通用名称For resource types that you mostly access through a different resource, you can use a generic name that is hard-coded in the template. 例如,可为 SQL Server 上的防火墙规则设置一个标准的通用名称:For example, you can set a standard, generic name for firewall rules on a SQL server:

{
  "type": "firewallrules",
  "name": "AllowAllWindowsAzureIps",
  ...
}

资源位置Resource location

部署模板时,必须提供每个资源的位置。When deploying a template, you must provide a location for each resource. 不同位置支持的资源类型不一样。Different resource types are supported in different locations. 若要获取资源类型支持的位置,请参阅 Azure 资源提供程序和类型To get the supported locations for a resource type, see Azure resource providers and types.

使用参数指定资源的位置,并将默认值设置为 resourceGroup().locationUse a parameter to specify the location for resources, and set the default value to resourceGroup().location.

以下示例显示了部署到作为参数指定的位置的存储帐户:The following example shows a storage account that is deployed to a location specified as a parameter:

{
  "$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"
      }
    },
    "location": {
      "type": "string",
      "defaultValue": "[resourceGroup().location]",
      "metadata": {
        "description": "Location for all resources."
      }
    }
  },
  "variables": {
    "storageAccountName": "[concat('storage', uniquestring(resourceGroup().id))]"
  },
  "resources": [
    {
      "type": "Microsoft.Storage/storageAccounts",
      "name": "[variables('storageAccountName')]",
      "location": "[parameters('location')]",
      "apiVersion": "2018-07-01",
      "sku": {
        "name": "[parameters('storageAccountType')]"
      },
      "kind": "StorageV2",
      "properties": {}
    }
  ],
  "outputs": {
    "storageAccountName": {
      "type": "string",
      "value": "[variables('storageAccountName')]"
    }
  }
}

子资源Child resources

在某些资源类型内,还可以定义子资源数组。Within some resource types, you can also define an array of child resources. 子资源是只存在于另一资源的上下文内的资源。Child resources are resources that only exist within the context of another resource. 例如,如果没有 SQL 服务器,则不存在 SQL 数据库;因此,此数据库是此服务器的子资源。For example, a SQL database can't exist without a SQL server so the database is a child of the server. 可以在此 Server 的定义内定义此数据库。You can define the database within the definition for the server.

{
  "apiVersion": "2015-05-01-preview",
  "type": "Microsoft.Sql/servers",
  "name": "exampleserver",
  ...
  "resources": [
    {
      "apiVersion": "2017-10-01-preview",
      "type": "databases",
      "name": "exampledatabase",
      ...
    }
  ]
}

但是,无需在服务器内定义数据库。But, you don't have to define the database within the server. 可以定义顶级子资源。You can define the child resource at the top level. 如果父资源未部署在同一模板中,或者想要使用 copy 创建多个子资源,可以使用此方法。You might use this approach if the parent resource isn't deployed in the same template, or if want to use copy to create more than one child resource. 使用此方法时,必须提供完整的资源类型,并将父资源名称包括在子资源名称中。With this approach, you must provide the full resource type, and include the parent resource name in the child resource name.

{
  "apiVersion": "2015-05-01-preview",
  "type": "Microsoft.Sql/servers",
  "name": "exampleserver",
  "resources": [ 
  ],
  ...
},
{
  "apiVersion": "2017-10-01-preview",
  "type": "Microsoft.Sql/servers/databases",
  "name": "exampleserver/exampledatabase",
  ...
}

为类型和名称提供的值根据子资源是在父资源的内部还是外部定义而异。The values you provide for type and name vary based on whether the child resource is defined within the parent resource or outside of the parent resource.

如果嵌套在父资源中,请使用:When nested in the parent resource, use:

"type": "{child-resource-type}",
"name": "{child-resource-name}",

如果在父资源的外部定义,请使用:When defined outside of the parent resource, use:

"type": "{resource-provider-namespace}/{parent-resource-type}/{child-resource-type}",
"name": "{parent-resource-name}/{child-resource-name}",

如果是嵌套的,则类型将设置为 databases,但完整资源类型仍为 Microsoft.Sql/servers/databasesWhen nested, the type is set to databases but its full resource type is still Microsoft.Sql/servers/databases. 可不提供 Microsoft.Sql/servers/,因为假设它继承父资源类型。You don't provide Microsoft.Sql/servers/ because it's assumed from the parent resource type. 子资源名称设置为 exampledatabase ,但完整名称包括父名称。The child resource name is set to exampledatabase but the full name includes the parent name. 可不提供 exampleserver,因为假设它继承父资源。You don't provide exampleserver because it's assumed from the parent resource.

向资源构造完全限定的引用时,类型和名称的分段组合顺序并不是这两者的简单串联。When constructing a fully qualified reference to a resource, the order to combine segments from the type and name isn't simply a concatenation of the two. 而是,在命名空间后面,使用类型/名称对的序列(从最不具体到最具体):Instead, after the namespace, use a sequence of type/name pairs from least specific to most specific:

{resource-provider-namespace}/{parent-resource-type}/{parent-resource-name}[/{child-resource-type}/{child-resource-name}]*

例如:For example:

Microsoft.Compute/virtualMachines/myVM/extensions/myExt 正确,Microsoft.Compute/virtualMachines/extensions/myVM/myExt 不正确Microsoft.Compute/virtualMachines/myVM/extensions/myExt is correct Microsoft.Compute/virtualMachines/extensions/myVM/myExt is not correct

输出Outputs

在 Outputs 节中,可以指定从部署返回的值。In the Outputs section, you specify values that are returned from deployment. 一般情况下,将从已部署的资源返回值。Typically, you return values from resources that were deployed.

可用属性Available properties

以下示例演示了输出定义的结构:The following example shows the structure of an output definition:

"outputs": {
  "<outputName>" : {
    "condition": "<boolean-value-whether-to-output-value>",
    "type" : "<type-of-output-value>",
    "value": "<output-value-expression>"
  }
}
元素名称Element name 必须Required 说明Description
outputNameoutputName Yes 输出值的名称。Name of the output value. 必须是有效的 JavaScript 标识符。Must be a valid JavaScript identifier.
条件condition No 指示此输出值是否返回的布尔值。Boolean value that indicates whether this output value is returned. 如果为 true,则该值包含在部署的输出中。When true, the value is included in the output for the deployment. 如果为 false,则此部署将跳过输出值。When false, the output value is skipped for this deployment. 如果未指定,则默认值为 trueWhen not specified, the default value is true.
typetype Yes 输出值的类型。Type of the output value. 输出值支持的类型与模板输入参数相同。Output values support the same types as template input parameters. 如果指定 securestring 作为输出类型,则值不会显示在部署历史记录中,并且无法从另一个模板检索。If you specify securestring for the output type, the value isn't displayed in the deployment history and can't be retrieved from another template. 若要在多个模板中使用机密值,请在 Key Vault 中存储该机密,并在参数文件中引用该机密。To use a secret value in more than one template, store the secret in a Key Vault and reference the secret in the parameter file. 有关详细信息,请参阅在部署过程中使用 Azure Key Vault 传递安全参数值For more information, see Use Azure Key Vault to pass secure parameter value during deployment.
valuevalue Yes 要求值并作为输出值返回的模板语言表达式。Template language expression that is evaluated and returned as output value.

定义和使用输出值Define and use output values

以下示例显示如何返回公共 IP 地址的资源 ID:The following example shows how to return the resource ID for a public IP address:

"outputs": {
  "resourceID": {
    "type": "string",
    "value": "[resourceId('Microsoft.Network/publicIPAddresses', parameters('publicIPAddresses_name'))]"
  }
}

下一个示例显示如何根据是否部署了新的资源 ID 有条件地返回公共 IP 地址的资源 ID:The next example shows how to conditionally return the resource ID for a public IP address based on whether a new one was deployed:

"outputs": {
  "resourceID": {
    "condition": "[equals(parameters('publicIpNewOrExisting'), 'new')]",
    "type": "string",
    "value": "[resourceId('Microsoft.Network/publicIPAddresses', parameters('publicIPAddresses_name'))]"
  }
}

有关条件输出的简单示例,请参阅条件输出模板For a simple example of conditional output, see conditional output template.

部署以后,可以使用脚本来检索该值。After the deployment, you can retrieve the value with script. 对于 PowerShell,请使用:For PowerShell, use:

(Get-AzResourceGroupDeployment -ResourceGroupName <resource-group-name> -Name <deployment-name>).Outputs.resourceID.value

对于 Azure CLI,请使用:For Azure CLI, use:

az group deployment show -g <resource-group-name> -n <deployment-name> --query properties.outputs.resourceID.value

可以使用 reference 函数从链接的模板检索输出值。You can retrieve the output value from a linked template by using the reference function. 若要从链接模板中获取输出值,请使用如下所示的语法检索属性值:"[reference('deploymentName').outputs.propertyName.value]"To get an output value from a linked template, retrieve the property value with syntax like: "[reference('deploymentName').outputs.propertyName.value]".

从链接模板获取输出属性时,属性名称不能包含短划线。When getting an output property from a linked template, the property name can't include a dash.

以下示例演示如何通过从链接模板检索值,在负载均衡器上设置 IP 地址。The following example shows how to set the IP address on a load balancer by retrieving a value from a linked template.

"publicIPAddress": {
  "id": "[reference('linkedTemplate').outputs.resourceID.value]"
}

不能在嵌套模板的 outputs 节中使用 reference 函数。You can't use the reference function in the outputs section of a nested template. 若要返回嵌套模板中部署的资源的值,请将嵌套模板转换为链接模板。To return the values for a deployed resource in a nested template, convert your nested template to a linked template.

输出示例模板Output example templates

模板Template 说明Description
复制变量Copy variables 创建复杂变量并输出这些值。Creates complex variables and outputs those values. 不部署任何资源。Doesn't deploy any resources.
公共 IP 地址Public IP address 创建公共 IP 地址并输出资源 ID。Creates a public IP address and outputs the resource ID.
负载均衡器Load balancer 链接到前面的模板。Links to the preceding template. 创建负载平衡器时,使用输出中的资源 ID。Uses the resource ID in the output when creating the load balancer.

注释和元数据Comments and metadata

可通过几个选项向模板添加注释和元数据。You have a few options for adding comments and metadata to your template.

几乎可以在模板中的任意位置添加 metadata 对象。You can add a metadata object almost anywhere in your template. 资源管理器会忽略该对象,但 JSON 编辑器可能会警告你该属性无效。Resource Manager ignores the object, but your JSON editor may warn you that the property isn't valid. 在对象中,定义所需的属性。In the object, define the properties you need.

{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "metadata": {
    "comments": "This template was developed for demonstration purposes.",
    "author": "Example Name"
  },

对于参数,添加具有 description 属性的 metadata 对象 。For parameters, add a metadata object with a description property.

"parameters": {
  "adminUsername": {
    "type": "string",
    "metadata": {
      "description": "User name for the Virtual Machine."
    }
  },

通过门户部署模板时,在说明中提供的文本自动用作该参数的提示。When deploying the template through the portal, the text you provide in the description is automatically used as a tip for that parameter.

显示参数提示

对于资源,添加 comments 元素或元数据对象 。For resources, add a comments element or a metadata object. 以下示例同时显示了注释元素和元数据对象。The following example shows both a comments element and a metadata object.

"resources": [
  {
    "comments": "Storage account used to store VM disks",
    "apiVersion": "2018-07-01",
    "type": "Microsoft.Storage/storageAccounts",
    "name": "[concat('storage', uniqueString(resourceGroup().id))]",
    "location": "[parameters('location')]",
    "metadata": {
      "comments": "These tags are needed for policy compliance."
    },
    "tags": {
      "Dept": "[parameters('deptName')]",
      "Environment": "[parameters('environment')]"
    },
    "sku": {
      "name": "Standard_LRS"
    },
    "kind": "Storage",
    "properties": {}
  }
]

对于输出,将元数据对象添加到输出值 。For outputs, add a metadata object to the output value.

"outputs": {
  "hostname": {
    "type": "string",
    "value": "[reference(variables('publicIPAddressName')).dnsSettings.fqdn]",
    "metadata": {
      "comments": "Return the fully qualified domain name"
    }
  },

无法将元数据对象添加到用户定义的函数。You can't add a metadata object to user-defined functions.

对于内联注释,可使用 //,但此语法不适用于所有工具。For inline comments, you can use // but this syntax doesn't work with all tools. 无法使用 Azure CLI 来部署带有内联注释的模板。You can't use Azure CLI to deploy the template with inline comments. 而且,无法使用门户模板编辑器处理带有内联注释的模板。And, you can't use the portal template editor to work on templates with inline comments. 如果添加此类注释,请务必使用支持内联 JSON 注释的工具。If you add this style of comment, be sure the tools you use support inline JSON comments.

{
  "type": "Microsoft.Compute/virtualMachines",
  "name": "[variables('vmName')]", // to customize name, change it in variables
  "location": "[parameters('location')]", //defaults to resource group location
  "apiVersion": "2018-10-01",
  "dependsOn": [ // storage account and network interface must be deployed first
    "[resourceId('Microsoft.Storage/storageAccounts/', variables('storageAccountName'))]",
    "[resourceId('Microsoft.Network/networkInterfaces/', variables('nicName'))]"
  ],

在 VS Code 中,可以将语言模式设置为带注释的 JSON。In VS Code, you can set the language mode to JSON with comments. 内联注释不再标记为无效。The inline comments are no longer marked as invalid. 更改模式:To change the mode:

  1. 打开语言模式选择 (Ctrl+K M)Open language mode selection (Ctrl+K M)

  2. 选择“带注释的 JSON” 。Select JSON with Comments.

    选择语言模式

快速入门和教程Quickstarts and tutorials

使用以下快速入门和教程了解如何开发资源管理器模板:Use the following quickstarts and tutorials to learn how to develop resource manager templates:

  • 快速入门Quickstarts

    标题Title 说明Description
    使用 Azure 门户Use the Azure portal 使用门户生成模板,并了解模板的编辑和部署过程。Generate a template using the portal, and understand the process of editing and deploying the template.
    使用 Visual Studio CodeUse Visual Studio Code 使用 Visual Studio Code 创建和编辑模板,以及如何使用 Azure Shell 部署模板。Use Visual Studio Code to create and edit templates, and how to use the Azure Shell to deploy templates.
    使用 Visual StudioUse Visual Studio 使用 Visual Studio 创建、编辑和部署模板。Use Visual Studio to create, edit, and deploy templates.
  • 教程Tutorials

    标题Title 说明Description
    利用模板参考Utilize template reference 利用模板参考文档来开发模板。Utilize the template reference documentation to develop templates. 在本教程中,找到存储帐户架构,并使用相关信息来创建加密的存储帐户。In the tutorial, you find the storage account schema, and use the information to create an encrypted storage account.
    创建多个实例Create multiple instances 创建多个 Azure 资源的实例。Create multiple instances of Azure resources. 在本教程中,将创建多个存储帐户实例。In the tutorial, you create multiple instances of storage account.
    设置资源部署顺序Set resource deployment order 定义资源依赖关系。Define resource dependencies. 在本教程中,将创建虚拟网络、虚拟机和相关 Azure 资源。In the tutorial, you create a virtual network, a virtual machine, and the dependent Azure resources. 了解如何定义依赖关系。You learn how the dependencies are defined.
    使用条件Use conditions 基于某些参数值来部署资源。Deploy resources based on some parameter values. 在本教程中,基于参数的值定义一个模板以创建新的存储帐户或使用现有存储帐户。In the tutorial, you define a template to create a new storage account or use an existing storage account based on the value of a parameter.
    集成 Key VaultIntegrate key vault 从 Azure Key Vault 检索机密/密码。Retrieve secrets/passwords from Azure Key Vault. 在本教程中,将创建虚拟机。In the tutorial, you create a virtual machine. 从 Key Vault 检索虚拟机管理员密码。The virtual machine administrator password is retrieved from a Key Vault.
    创建链接模板Create linked templates 模块化模板,并从模板中调用其他模板。Modularize templates, and call other templates from a template. 在本教程中,将创建虚拟网络、虚拟机和相关资源。In the tutorial, you create a virtual network, a virtual machine, and the dependent resources. 相关存储帐户在链接模板中定义。The dependent storage account is defined in a linked template.
    部署虚拟机扩展Deploy virtual machine extensions 使用扩展执行部署后任务。Perform post-deployment tasks by using extensions. 在本教程中,你将部署客户脚本扩展以在虚拟机上安装 Web 服务器。In the tutorial, you deploy a customer script extension to install web server on the virtual machine.
    部署 SQL 扩展Deploy SQL extensions 使用扩展执行部署后任务。Perform post-deployment tasks by using extensions. 在本教程中,你将部署客户脚本扩展以在虚拟机上安装 Web 服务器。In the tutorial, you deploy a customer script extension to install web server on the virtual machine.
    保护项目Secure artifacts 保护完成部署所需的项目。Secure the artifacts needed to complete the deployments. 本教程介绍如何保护“部署 SQL 扩展”教程中使用的项目。In the tutorial, you learn how to secure the artifact used in the Deploy SQL extensions tutorial.
    教程:对资源管理器模板部署进行故障排除Tutorial: Troubleshoot Resource Manager template deployments 排查模板部署问题。Troubleshoot template deployment issues.

这些教程可以单独使用,也可以作为一系列用于学习主要的资源管理器模板开发概念。These tutorials can be used individually, or as a series to learn the major Resource Manager template development concepts.

后续步骤Next steps