了解 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.

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

模板格式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.
parametersparameters 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.

参数Parameters

在模板的 parameters 节中,可以指定在部署资源时能够输入的值。In the parameters section of the template, you specify which values you can input when deploying the resources. 一个模板中最多可以有 256 个参数。You're limited to 256 parameters in a template. 可以通过使用包含多个属性的对象来减少参数的数目。You can reduce the number of parameters by using objects that contain multiple 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
parameter-nameparameter-name 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.
descriptiondescription No 通过门户向用户显示的参数的说明。Description of the parameter that is displayed to users through the portal. 有关详细信息,请参阅模板中的注释For more information, see Comments in templates.

有关如何使用参数的示例,请参阅 Azure 资源管理器模板中的参数For examples of how to use parameters, see Parameters in Azure Resource Manager templates.

变量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.

以下示例演示了可用于定义变量的选项: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.

有关如何使用变量的示例,请参阅 Azure 资源管理器模板中的变量For examples of how to use variables, see Variables in Azure Resource Manager template.

函数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.
"functions": [
  {
    "namespace": "<namespace-for-functions>",
    "members": {
      "<function-name>": {
        "parameters": [
          {
            "name": "<parameter-name>",
            "type": "<type-of-parameter-value>"
          }
        ],
        "output": {
          "type": "<type-of-output-value>",
          "value": "<function-return-value>"
        }
      }
    }
  }
],
元素名称Element name 必须Required 说明Description
命名空间namespace Yes 自定义函数的命名空间。Namespace for the custom functions. 用于避免与模板函数的命名冲突。Use to avoid naming conflicts with template functions.
function-namefunction-name Yes 自定义函数的名称。Name of the custom function. 调用函数时,将函数名称与命名空间组合在一起。When calling the function, combine the function name with the namespace. 例如,若要在命名空间 contoso 中调用名为 uniqueName 的函数,请使用 "[contoso.uniqueName()]"For example, to call a function named uniqueName in the namespace contoso, use "[contoso.uniqueName()]".
parameter-nameparameter-name No 要在自定义函数中使用的参数的名称。Name of the parameter to be used within the custom function.
parameter-valueparameter-value No 参数值的类型。Type of the parameter value. 允许的类型和值为 stringsecurestringintboolobjectsecureObjectarrayThe allowed types and values are string, securestring, int, bool, object, secureObject, and array.
output-typeoutput-type Yes 输出值的类型。Type of the output value. 输出值支持的类型与函数输入参数相同。Output values support the same types as function input parameters.
output-valueoutput-value Yes 由函数计算并返回的模板语言表达式。Template language expression that is evaluated and returned from the function.

有关如何使用自定义函数的示例,请参阅 Azure 资源管理器模板中的用户定义函数For examples of how to use custom functions, see User-defined functions in Azure Resource Manager template.

资源Resources

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

使用以下结构定义资源: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
conditioncondition 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.
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). 对于子资源,类型的格式取决于该资源是嵌套在父资源中,还是在父资源的外部定义。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 Set name and type for child resources.
namename Yes 资源的名称。Name of the resource. 该名称必须遵循 RFC3986 中定义的 URI 构成部分限制。The name must follow URI component restrictions defined in RFC3986. 向外部各方公开资源名称的 Azure 服务会验证名称,以确保它不是试图窃取另一标识。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 Set name and type for 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. 请参阅设置资源位置See Set resource location.
tagstags No 与资源关联的标记。Tags that are associated with the resource. 应用可以在订阅中对资源进行逻辑组织的标记。Apply tags to logically organize resources across your subscription.
commentscomments No 用于描述模板中资源的注释。Your notes for documenting the resources in your template. 有关详细信息,请参阅模板中的注释For more information, see Comments in templates.
copycopy 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.
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.
planplan No 某些资源接受定义了要部署的计划的值。Some resources allow values that define the plan to deploy. 例如,可以为虚拟机指定市场映像。For example, you can specify the marketplace image for a virtual machine.
resourcesresources 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 Set name and type for child resources.

输出Outputs

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

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

"outputs": {
  "<output-name>" : {
    "condition": "<boolean-value-whether-to-output-value>",
    "type" : "<type-of-output-value>",
    "value": "<output-value-expression>"
  }
}
元素名称Element name 必须Required 说明Description
output-nameoutput-name Yes 输出值的名称。Name of the output value. 必须是有效的 JavaScript 标识符。Must be a valid JavaScript identifier.
conditioncondition 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.

有关如何使用输出的示例,请参阅 Azure 资源管理器模板中的输出For examples of how to use outputs, see Outputs in Azure Resource Manager template.

注释和元数据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.

    选择语言模式

后续步骤Next steps