ARM 模板的资源函数

资源管理器提供了以下函数,用于获取 Azure 资源管理器模板(ARM 模板)中的资源值:

若要从参数、变量或当前部署获取值,请参阅 Deployment value functions(部署值函数)。

要获取部署范围值,请参阅 Scope 函数

提示

建议使用 Bicep,因为它提供与 ARM 模板相同的功能,并且该语法更易于使用。 若要了解详细信息,请参阅资源函数。

extensionResourceId

extensionResourceId(baseResourceId, resourceType, resourceName1, [resourceName2], ...)

返回扩展资源的资源 ID。 扩展资源是一种资源类型,可应用于扩充另一资源的功能。

在 Bicep 中,使用 extensionResourceId 函数。

parameters

参数 必选 类型​​ 说明
baseResourceId 字符串 扩展资源应用到的资源的资源 ID。
resourceType 字符串 扩展资源的类型,包括资源提供程序命名空间。
resourceName1 字符串 扩展资源的名称。
resourceName2 字符串 下一个资源名称段(如果需要)。

如果资源类型包含更多段,则继续添加资源名称作为参数。

返回值

此函数返回的资源 ID 的基本格式为:

{scope}/providers/{extensionResourceProviderNamespace}/{extensionResourceType}/{extensionResourceName}

作用域段因所扩展的基础资源而异。 例如,订阅的 ID 有不同于资源组的 ID 的段。

当扩展资源应用到某个资源时,资源 ID 以下述格式返回:

/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{baseResourceProviderNamespace}/{baseResourceType}/{baseResourceName}/providers/{extensionResourceProviderNamespace}/{extensionResourceType}/{extensionResourceName}

将扩展资源应用到资源组时,返回的格式为:

/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{extensionResourceProviderNamespace}/{extensionResourceType}/{extensionResourceName}

下一部分演示一个将此函数与资源组配合使用的示例。

将扩展资源应用到订阅时,返回的格式为:

/subscriptions/{subscriptionId}/providers/{extensionResourceProviderNamespace}/{extensionResourceType}/{extensionResourceName}

将扩展资源应用到管理组时,返回的格式为:

/providers/Microsoft.Management/managementGroups/{managementGroupName}/providers/{extensionResourceProviderNamespace}/{extensionResourceType}/{extensionResourceName}

下一部分演示一个将此函数与管理组配合使用的示例。

extensionResourceId 示例

以下示例返回资源组锁的资源 ID。

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "lockName": {
      "type": "string"
    }
  },
  "variables": {},
  "resources": [],
  "outputs": {
    "lockResourceId": {
      "type": "string",
      "value": "[extensionResourceId(resourceGroup().Id , 'Microsoft.Authorization/locks', parameters('lockName'))]"
    }
  }
}

部署到管理组的自定义策略定义是作为扩展资源实现的。 若要创建和分配策略,请将以下模板部署到管理组。

{
  "$schema": "https://schema.management.azure.com/schemas/2019-08-01/managementGroupDeploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "metadata": {
    "_generator": {
      "name": "bicep",
      "version": "0.5.6.12127",
      "templateHash": "1532257987028557958"
    }
  },
  "parameters": {
    "targetMG": {
      "type": "string",
      "metadata": {
        "description": "Target Management Group"
      }
    },
    "allowedLocations": {
      "type": "array",
      "defaultValue": [
        "chinanorth2",
        "chinanorth3",
        "chinanorth"
      ],
      "metadata": {
        "description": "An array of the allowed locations, all other locations will be denied by the created policy."
      }
    }
  },
  "variables": {
    "mgScope": "[tenantResourceId('Microsoft.Management/managementGroups', parameters('targetMG'))]",
    "policyDefinitionName": "LocationRestriction"
  },
  "resources": [
    {
      "type": "Microsoft.Authorization/policyDefinitions",
      "apiVersion": "2020-03-01",
      "name": "[variables('policyDefinitionName')]",
      "properties": {
        "policyType": "Custom",
        "mode": "All",
        "parameters": {},
        "policyRule": {
          "if": {
            "not": {
              "field": "location",
              "in": "[parameters('allowedLocations')]"
            }
          },
          "then": {
            "effect": "deny"
          }
        }
      }
    },
    {
      "type": "Microsoft.Authorization/policyAssignments",
      "apiVersion": "2020-03-01",
      "name": "location-lock",
      "properties": {
        "scope": "[variables('mgScope')]",
        "policyDefinitionId": "[extensionResourceId(variables('mgScope'), 'Microsoft.Authorization/policyDefinitions', variables('policyDefinitionName'))]"
      },
      "dependsOn": [
        "[extensionResourceId(managementGroup().id, 'Microsoft.Authorization/policyDefinitions', variables('policyDefinitionName'))]"
      ]
    }
  ]
}

内置策略定义是租户级别的资源。 有关部署内置策略定义的示例,请参阅 tenantResourceId

list*

list{Value}(resourceName or resourceIdentifier, apiVersion, functionValues)

此函数的语法因列表操作的名称而异。 每个实现都为支持列表操作的资源类型返回值。 操作名称必须以 list 开头,并且可以有后缀。 以下是几个常见示例:listlistKeyslistKeyValuelistSecrets

在 Bicep 中,使用 list* 函数。

parameters

参数 必选 类型​​ 说明
resourceName 或 resourceIdentifier 字符串 资源的唯一标识符。
apiVersion 字符串 资源运行时状态的 API 版本。 通常采用 yyyy-mm-dd格式。
functionValues object 具有函数值的对象。 仅为支持接收具有参数值的对象的函数提供此对象,例如存储帐户上的 listAccountSas。 本文中演示了传递函数值的示例。

有效使用

列表函数可以在资源定义的属性中使用。 请勿使用在模板的 outputs 节中公开敏感信息的列表函数。 输出值存储在部署历史记录中,可能会被恶意用户检索到。

属性迭代一起使用时,可以使用 input 的 list 函数,因为表达式已分配给资源属性。 不能将它们与 count 一起使用,因为必须在解析 list 函数之前确定计数。

实现形式

下表中显示 list* 的可能用途。

资源类型 函数名称
Microsoft.Addons/supportProviders listsupportplaninfo
Microsoft.AnalysisServices/servers listGatewayStatus
Microsoft.ApiManagement/service/authorizationServers listSecrets
Microsoft.ApiManagement/service/gateways listKeys
Microsoft.ApiManagement/service/identityProviders listSecrets
Microsoft.ApiManagement/service/namedValues listValue
Microsoft.ApiManagement/service/openidConnectProviders listSecrets
Microsoft.ApiManagement/service/subscriptions listSecrets
Microsoft.AppConfiguration/configurationStores ListKeys
Microsoft.AppPlatform/Spring listTestKeys
Microsoft.Automation/automationAccounts listKeys
Microsoft.Batch/batchAccounts listKeys
Microsoft.CognitiveServices/accounts listKeys
Microsoft.ContainerRegistry/registries listBuildSourceUploadUrl
Microsoft.ContainerRegistry/registries listCredentials
Microsoft.ContainerRegistry/registries listUsages
Microsoft.ContainerRegistry/registries/agentpools listQueueStatus
Microsoft.ContainerRegistry/registries/buildTasks listSourceRepositoryProperties
Microsoft.ContainerRegistry/registries/buildTasks/steps listBuildArguments
Microsoft.ContainerRegistry/registries/taskruns listDetails
Microsoft.ContainerRegistry/registries/webhooks listEvents
Microsoft.ContainerRegistry/registries/runs listLogSasUrl
Microsoft.ContainerRegistry/registries/tasks listDetails
Microsoft.ContainerService/managedClusters listClusterAdminCredential
Microsoft.ContainerService/managedClusters listClusterMonitoringUserCredential
Microsoft.ContainerService/managedClusters listClusterUserCredential
Microsoft.ContainerService/managedClusters/accessProfiles listCredential
Microsoft.DataBox/jobs listCredentials
Microsoft.DataFactory/datafactories/gateways listauthkeys
Microsoft.DataFactory/factories/integrationruntimes listauthkeys
Microsoft.Devices/iotHubs listKeys
Microsoft.Devices/iotHubs/iotHubKeys listKeys
Microsoft.Devices/provisioningServices/keys listKeys
Microsoft.Devices/provisioningServices listKeys
Microsoft.DevTestLab/labs/users/serviceFabrics ListApplicableSchedules
Microsoft.DocumentDB/databaseAccounts listKeys
Microsoft.DocumentDB/databaseAccounts/notebookWorkspaces listConnectionInfo
Microsoft.DomainRegistration/topLevelDomains listAgreements
Microsoft.EventHub/namespaces/authorizationRules listKeys
Microsoft.EventHub/namespaces/disasterRecoveryConfigs/authorizationRules listKeys
Microsoft.EventHub/namespaces/eventhubs/authorizationRules listKeys
Microsoft.ImportExport/jobs listBitLockerKeys
Microsoft.Kusto/Clusters/Databases ListPrincipals
Microsoft.Logic/integrationAccounts/agreements listContentCallbackUrl
Microsoft.Logic/integrationAccounts/assemblies listContentCallbackUrl
Microsoft.Logic/integrationAccounts listCallbackUrl
Microsoft.Logic/integrationAccounts listKeyVaultKeys
Microsoft.Logic/integrationAccounts/maps listContentCallbackUrl
Microsoft.Logic/integrationAccounts/partners listContentCallbackUrl
Microsoft.Logic/integrationAccounts/schemas listContentCallbackUrl
Microsoft.Logic/workflows listCallbackUrl
Microsoft.Logic/workflows listSwagger
Microsoft.Logic/workflows/runs/actions listExpressionTraces
Microsoft.Logic/workflows/runs/actions/repetitions listExpressionTraces
Microsoft.Logic/workflows/triggers listCallbackUrl
Microsoft.Logic/workflows/versions/triggers listCallbackUrl
Microsoft.Media/mediaservices/assets listContainerSas
Microsoft.Media/mediaservices/assets listStreamingLocators
Microsoft.Media/mediaservices/streamingLocators listContentKeys
Microsoft.Media/mediaservices/streamingLocators listPaths
Microsoft.Network/applicationSecurityGroups listIpConfigurations
Microsoft.NotificationHubs/Namespaces/authorizationRules listkeys
Microsoft.NotificationHubs/Namespaces/NotificationHubs/authorizationRules listkeys
Microsoft.OperationalInsights/workspaces list
Microsoft.OperationalInsights/workspaces listKeys
Microsoft.PolicyInsights/remediations listDeployments
Microsoft.Relay/namespaces/authorizationRules listKeys
Microsoft.Relay/namespaces/disasterRecoveryConfigs/authorizationRules listKeys
Microsoft.Relay/namespaces/HybridConnections/authorizationRules listKeys
Microsoft.Relay/namespaces/WcfRelays/authorizationRules listkeys
Microsoft.Search/searchServices listAdminKeys
Microsoft.Search/searchServices listQueryKeys
Microsoft.ServiceBus/namespaces/authorizationRules listKeys
Microsoft.ServiceBus/namespaces/disasterRecoveryConfigs/authorizationRules listKeys
Microsoft.ServiceBus/namespaces/queues/authorizationRules listKeys
Microsoft.SignalRService/SignalR listKeys
Microsoft.Storage/storageAccounts listAccountSas
Microsoft.Storage/storageAccounts listKeys
Microsoft.Storage/storageAccounts listServiceSas
Microsoft.Synapse/workspaces/integrationRuntimes listAuthKeys
Microsoft.Web/connectionGateways ListStatus
microsoft.web/connections listconsentlinks
Microsoft.Web/customApis listWsdlInterfaces
microsoft.web/locations listwsdlinterfaces
microsoft.web/apimanagementaccounts/apis/connections listconnectionkeys
microsoft.web/apimanagementaccounts/apis/connections listSecrets
microsoft.web/sites/backups list
Microsoft.Web/sites/config list
microsoft.web/sites/functions listKeys
microsoft.web/sites/functions listSecrets
microsoft.web/sites/hybridconnectionnamespaces/relays listKeys
microsoft.web/sites listsyncfunctiontriggerstatus
microsoft.web/sites/slots/functions listSecrets
microsoft.web/sites/slots/backups list
Microsoft.Web/sites/slots/config list
microsoft.web/sites/slots/functions listSecrets

若要确定哪些资源类型具有列表操作,请使用以下选项:

  • 查看资源提供程序的 REST API 操作,并查找列表操作。 例如,存储帐户具有 listKeys 操作

  • 使用 Get-​AzProvider​Operation PowerShell cmdlet。 以下示例获取存储帐户的所有列表操作:

    Get-AzProviderOperation -OperationSearchString "Microsoft.Storage/*" | where {$_.Operation -like "*list*"} | FT Operation
    
  • 使用以下 Azure CLI 命令,仅筛选列表操作:

    az provider operation show --namespace Microsoft.Storage --query "resourceTypes[?name=='storageAccounts'].operations[].name | [?contains(@, 'list')]"
    

返回值

返回的对象因使用的 list 函数而异。 例如,用于存储帐户的 listKeys 返回以下格式:

{
  "keys": [
    {
      "keyName": "key1",
      "permissions": "Full",
      "value": "{value}"
    },
    {
      "keyName": "key2",
      "permissions": "Full",
      "value": "{value}"
    }
  ]
}

其他 list 函数具有不同的返回格式。 若要查看函数的格式,请将其包含在 outputs 节中,如示例模板所示。

备注

使用资源名称或 resourceId 函数来指定资源。 在部署被引用资源的同一模板中使用 list 函数时,请使用资源名称。

如果在有条件部署的资源中使用 list 函数,则即使未部署该资源,也会对该函数求值。 如果 list 函数引用某个不存在的资源,则会出现错误。 使用 if 函数确保仅在部署资源时才评估函数。 请查看示例模板的 if 函数,该模板将 iflist 用于进行条件部署的资源。

List 示例

以下示例在为部署脚本设置值时使用了 listKeys

"storageAccountSettings": {
  "storageAccountName": "[variables('storageAccountName')]",
  "storageAccountKey": "[listKeys(resourceId('Microsoft.Storage/storageAccounts', variables('storageAccountName')), '2019-06-01').keys[0].value]"
}

下一个示例演示采用参数的 list 函数。 在本例中,函数为 listAccountSas。 请为到期时间传递一个对象。 到期时间必须是将来的时间。

"parameters": {
  "accountSasProperties": {
    "type": "object",
    "defaultValue": {
      "signedServices": "b",
      "signedPermission": "r",
      "signedExpiry": "2020-08-20T11:00:00Z",
      "signedResourceTypes": "s"
    }
  }
},
...
"sasToken": "[listAccountSas(parameters('storagename'), '2018-02-01', parameters('accountSasProperties')).accountSasToken]"

pickZones

pickZones(providerNamespace, resourceType, location, [numberOfZones], [offset])

确定资源类型是否支持指定位置或地区的区域。 此函数仅支持区域资源。 区域冗余服务返回空数组。 有关详细信息,请参阅支持可用性区域的 Azure 服务

在 Bicep 中,使用 pickZones 函数。

parameters

参数 必选 类型​​ 说明
providerNamespace 字符串 要检查是否有区域支持的资源类型的资源提供程序命名空间。
resourceType 字符串 要检查是否有区域支持的资源类型。
location 字符串 要检查是否有区域支持的地区。
numberOfZones integer 要返回的逻辑区域数。 默认值为 1。 该数字必须是 1 到 3 的正整数。 对于单区域资源,请使用 1。 对于多区域资源,该值必须小于或等于受支持区域的数量。
offset integer 起始逻辑区域的偏移量。 如果 offset 加上 numberOfZones 超过受支持区域的数量,函数将返回错误。

返回值

具有受支持区域的数组。 如果使用 offset 和 numberOfZones 的默认值,支持区域的资源类型和地区返回以下数组:

[
    "1"
]

numberOfZones 参数设置为 3 时,它将返回:

[
    "1",
    "2",
    "3"
]

如果资源类型或地区不支持区域,则返回空数组。 对于区域冗余服务,也会返回空数组。

[
]

备注

Azure 可用性区域有不同的类别:区域和区域冗余。 pickZones 函数可用于返回区域资源的可用性区域。 对于区域冗余服务 (ZRS),该函数将返回空数组。 区域资源通常有 zones 属性,位于资源定义的顶层。 若要确定可用性区域的支持类别,请参阅支持可用性区域 Azure 服务

若要确定给定的 Azure 区域或位置是否支持可用性区域,请使用区域资源类型调用 pickZones 函数,例如 Microsoft.Network/publicIPAddresses。 如果响应非空,则该区域支持可用性区域。

pickZones 示例

以下模板显示了使用 pickZones 函数的三个结果。

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {},
  "functions": [],
  "variables": {},
  "resources": [],
  "outputs": {
    "supported": {
      "type": "array",
      "value": "[pickZones('Microsoft.Compute', 'virtualMachines', 'chinaeast2')]"
    },
    "notSupportedRegion": {
      "type": "array",
      "value": "[pickZones('Microsoft.Compute', 'virtualMachines', 'chinanorth')]"
    },
    "notSupportedType": {
      "type": "array",
      "value": "[pickZones('Microsoft.Cdn', 'profiles', 'chinaeast2')]"
    }
  }
}

上述示例的输出返回三个数组。

名称 类型
受支持 array [ "1" ]
notSupportedRegion array []
notSupportedType array []

可以使用 pickZones 的响应来确定是为区域提供 null,还是将虚拟机分配给不同的区域。 下面的示例基于区域的可用性设置区域的值。

"zones": {
  "value": "[if(not(empty(pickZones('Microsoft.Compute', 'virtualMachines', 'chinanorth2'))), string(add(mod(copyIndex(),3),1)), json('null'))]"
},

Azure Cosmos DB 不是区域资源,但你可以使用 pickZones 函数来确定是否为异地复制启用区域冗余。 传递 Microsoft.Storage/storageAccounts 资源类型以确定是否启用区域冗余。

"resources": [
  {
    "type": "Microsoft.DocumentDB/databaseAccounts",
    "apiVersion": "2021-04-15",
    "name": "[variables('accountName_var')]",
    "location": "[parameters('location')]",
    "kind": "GlobalDocumentDB",
    "properties": {
      "consistencyPolicy": "[variables('consistencyPolicy')[parameters('defaultConsistencyLevel')]]",
      "locations": [
        {
          "locationName": "[parameters('primaryRegion')]",
          "failoverPriority": 0,
          "isZoneRedundant": "[if(empty(pickZones('Microsoft.Storage', 'storageAccounts', parameters('primaryRegion'))), bool('false'), bool('true'))]",
        },
        {
          "locationName": "[parameters('secondaryRegion')]",
          "failoverPriority": 1,
          "isZoneRedundant": "[if(empty(pickZones('Microsoft.Storage', 'storageAccounts', parameters('secondaryRegion'))), bool('false'), bool('true'))]",
        }
      ],
      "databaseAccountOfferType": "Standard",
      "enableAutomaticFailover": "[parameters('automaticFailover')]"
    }
  }
]

providers

在 ARM 模板中,providers 函数已弃用。 我们不再建议使用它。 如果你使用了此函数来获取资源提供程序的 API 版本,建议在模板中提供特定的 API 版本。 如果版本之间的属性发生更改,则使用动态返回的 API 版本可能会破坏模板。

在 Bicep 中,providers 函数已弃用。

providers 运算仍可通过 REST API 提供。 它可在 ARM 模板外部使用来获取有关资源提供程序的信息。

reference

在不包含符号名称的模板中:

reference(resourceName or resourceIdentifier, [apiVersion], ['Full'])

在包含符号名称的模板中:

reference(symbolicName or resourceIdentifier, [apiVersion], ['Full'])

返回表示资源的运行时状态的对象。 若要返回表示资源集合运行时状态的对象的数组,请参阅引用

Bicep 提供 reference 函数,但在大多数情况下,不需要 reference 函数。 建议改用资源的符号名称。 请参阅参考资料

参数

参数 必选 类型​​ 描述
resourceName/resourceIdentifier 或 symbolicName/resourceIdentifier string 在没有符号名称的模板中,指定资源的名称或唯一标识符。 当引用当前模板中的资源时,请仅提供资源名称作为参数。 当引用以前部署的资源或者资源名称不明确时,请提供资源 ID。
在包含符号名称的模板中,指定资源的符号名称或唯一标识符。 在引用当前模板中的资源时,请仅提供资源的符号名称作为参数。 当引用以前部署的资源时,请提供资源 ID。
apiVersion 字符串 指定的资源的 API 版本。 如果资源不是在同一模板中预配的,则需要此参数。 通常采用 yyyy-mm-dd格式。
'Full' 字符串 一个值,指定是否要返回完整资源对象。 如果未指定 'Full',仅返回资源的属性对象。 完整对象包括资源 ID 和位置等值。

返回值

每种资源类型返回 reference 函数的不同属性。 该函数不返回单个预定义的格式。 另外,返回的值因 'Full' 参数的值而异。 若要查看资源类型的属性,请返回 outputs 节中的对象,如示例所示。

备注

reference 函数检索以前部署的资源或在当前模板中部署的资源的运行时状态。 本文展示了这两种方案的示例。

通常情况下,可以使用 reference 函数返回对象的特定值,例如 blob 终结点 URI 或完全限定的域名。

"outputs": {
  "BlobUri": {
    "type": "string",
    "value": "[reference(resourceId('Microsoft.Storage/storageAccounts', parameters('storageAccountName'))).primaryEndpoints.blob]"
  },
  "FQDN": {
    "type": "string",
    "value": "[reference(resourceId('Microsoft.Network/publicIPAddresses', parameters('ipAddressName'))).dnsSettings.fqdn]"
  }
}

需要不属于属性架构的资源值时,请使用 'Full'。 例如,若要设置密钥保管库访问策略,请获取虚拟机的标识属性。

{
  "type": "Microsoft.KeyVault/vaults",
  "apiVersion": "2022-07-01",
  "name": "vaultName",
  "properties": {
    "tenantId": "[subscription().tenantId]",
    "accessPolicies": [
      {
        "tenantId": "[reference(resourceId('Microsoft.Compute/virtualMachines', variables('vmName')), '2019-03-01', 'Full').identity.tenantId]",
        "objectId": "[reference(resourceId('Microsoft.Compute/virtualMachines', variables('vmName')), '2019-03-01', 'Full').identity.principalId]",
        "permissions": {
          "keys": [
            "all"
          ],
          "secrets": [
            "all"
          ]
        }
      }
    ],
    ...

有效使用

reference 函数只能在模板或部署的输出部分或资源定义的 properties 对象中使用。 它不能用于资源属性,例如 typenamelocation 和资源定义的其他顶级属性。 与属性迭代一起使用时,可以使用 inputreference 函数,因为表达式已分配给资源属性。

不能使用 reference 函数在复制循环中设置 count 属性的值。 可用于在循环中设置其他属性。 count 属性的引用会被阻止,因为必须在解析 reference 函数之前确定该属性。

若要在嵌套模板的输出部分中使用 reference 函数或任何 list* 函数,必须将 expressionEvaluationOptions 设置为使用内层作用域计算或使用链接的而不是嵌套的模板。

如果在有条件部署的资源中使用 reference 函数,则会对该函数进行评估,即使资源尚未部署。 如果 reference 函数引用某个不存在的资源,则会出现错误。 使用 if 函数确保仅在部署资源时才评估函数。 请查看示例模板的 if 函数,该模板将 ifreference 用于进行条件部署的资源。

隐式依赖项

如果在同一模板内预配了被引用资源且通过其名称(而非资源 ID)引用该资源,则使用 reference 函数会隐式声明一个资源依赖于另一个资源。 也不需要同时使用 dependsOn 属性。 只有当引用的资源已完成部署后,才会对函数求值。

资源名称,符号名称或标识符

若要引用在同一无符号名称的模板中部署的资源,请提供该资源的名称。

"value": "[reference(parameters('storageAccountName'))]"

若要引用在同一包含符号名称的模板中部署的资源,请提供该资源的符号名称。

"value": "[reference('myStorage').primaryEndpoints]"

"value": "[reference('myStorage', '2022-09-01', 'Full').location]"

引用没有部署在同一模板中的资源时,请提供资源 ID 和 apiVersion

"value": "[reference(resourceId(parameters('storageResourceGroup'), 'Microsoft.Storage/storageAccounts', parameters('storageAccountName')), '2022-09-01')]"

若要避免所引用的资源不明确,可以提供完全限定的资源标识符。

"value": "[reference(resourceId('Microsoft.Network/publicIPAddresses', parameters('ipAddressName')))]"

向资源构造完全限定的引用时,类型和名称的分段组合顺序并不是这两者的简单串联。 而是,在命名空间后面,使用类型/名称对的序列(从最不具体到最具体):

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

例如:

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

若要简化任何资源 ID 的创建,请使用本文档中所述的 resourceId() 函数,而不是 concat() 函数。

获取托管标识

Azure 资源的托管标识是为某些资源隐式创建的扩展资源类型。 由于模板中未显式定义托管标识,因此必须引用该标识所应用到的资源。 使用 Full 获取所有属性,包括隐式创建的标识。

模式为:

"[reference(resourceId(<resource-provider-namespace>, <resource-name>), <API-version>, 'Full').Identity.propertyName]"

例如,若要获取应用于虚拟机的托管标识的主体 ID,请使用:

"[reference(resourceId('Microsoft.Compute/virtualMachines', variables('vmName')),'2019-12-01', 'Full').identity.principalId]",

或者,若要获取应用于虚拟机规模集的托管标识的租户 ID,请使用:

"[reference(resourceId('Microsoft.Compute/virtualMachineScaleSets',  variables('vmNodeType0Name')), 2019-12-01, 'Full').Identity.tenantId]"

Reference 示例

以下示例部署一个资源并引用该资源。

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "storageAccountName": {
      "type": "string"
    },
    "location": {
      "type": "string",
      "defaultValue": "[resourceGroup().location]"
    }
  },
  "resources": [
    {
      "type": "Microsoft.Storage/storageAccounts",
      "apiVersion": "2022-09-01",
      "name": "[parameters('storageAccountName')]",
      "location": "[parameters('location')]",
      "sku": {
        "name": "Standard_LRS"
      },
      "kind": "Storage",
      "tags": {},
      "properties": {
      }
    }
  ],
  "outputs": {
    "referenceOutput": {
      "type": "object",
      "value": "[reference(parameters('storageAccountName'))]"
    },
    "fullReferenceOutput": {
      "type": "object",
      "value": "[reference(parameters('storageAccountName'), '2022-09-01', 'Full')]"
    }
  }
}

上面的示例返回两个对象。 属性对象采用以下格式:

{
   "creationTime": "2017-10-09T18:55:40.5863736Z",
   "primaryEndpoints": {
     "blob": "https://examplestorage.blob.core.chinacloudapi.cn/",
     "file": "https://examplestorage.file.core.chinacloudapi.cn/",
     "queue": "https://examplestorage.queue.core.chinacloudapi.cn/",
     "table": "https://examplestorage.table.core.chinacloudapi.cn/"
   },
   "primaryLocation": "chinanorth3",
   "provisioningState": "Succeeded",
   "statusOfPrimary": "available",
   "supportsHttpsTrafficOnly": false
}

完整对象采用以下格式:

{
  "apiVersion":"2022-09-01",
  "location":"southchinanorth2",
  "sku": {
    "name":"Standard_LRS",
    "tier":"Standard"
  },
  "tags":{},
  "kind":"Storage",
  "properties": {
    "creationTime":"2021-10-09T18:55:40.5863736Z",
    "primaryEndpoints": {
      "blob":"https://examplestorage.blob.core.chinacloudapi.cn/",
      "file":"https://examplestorage.file.core.chinacloudapi.cn/",
      "queue":"https://examplestorage.queue.core.chinacloudapi.cn/",
      "table":"https://examplestorage.table.core.chinacloudapi.cn/"
    },
    "primaryLocation":"chinanorth3",
    "provisioningState":"Succeeded",
    "statusOfPrimary":"available",
    "supportsHttpsTrafficOnly":false
  },
  "subscriptionId":"<subscription-id>",
  "resourceGroupName":"functionexamplegroup",
  "resourceId":"Microsoft.Storage/storageAccounts/examplestorage",
  "referenceApiVersion":"2021-04-01",
  "condition":true,
  "isConditionTrue":true,
  "isTemplateResource":false,
  "isAction":false,
  "provisioningOperation":"Read"
}

以下示例模板引用的存储帐户未在此模板中部署。 同一订阅内已存在该存储帐户。

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "storageResourceGroup": {
      "type": "string"
    },
    "storageAccountName": {
      "type": "string"
    }
  },
  "resources": [],
  "outputs": {
    "ExistingStorage": {
      "type": "object",
      "value": "[reference(resourceId(parameters('storageResourceGroup'), 'Microsoft.Storage/storageAccounts', parameters('storageAccountName')), '2021-04-01')]"
    }
  }
}

引用

references(symbolic name of a resource collection, ['Full', 'Properties])

函数 references 的工作方式与 reference 类似。 references 函数不返回表示资源运行时状态的对象,而是返回表示资源集合的运行时状态的对象数组。 此函数需要 ARM 模板语言版本 2.0,并且启用了符号名称

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "languageVersion": "2.0",
  "contentVersion": "1.0.0.0",
  ...
}

在 Bicep 中,没有显式 references 函数。 相反,符号集合用法是直接使用的,在代码生成期间,Bicep 将其转换为利用 ARM 模板 references 函数的 ARM 模板。 有关详细信息,请参阅参考资源/模块集合

参数

参数 必选 类型​​ 描述
资源集合的符号名称 string 当前模板中定义的资源集合的符号名称。 函数 references 不支持引用当前模板外部的资源。
“Full”、“Properties” string 一个值,指定是否要返回完整资源对象数组。 默认值为 'Properties'。 如果未指定 'Full',仅返回资源的属性对象。 完整对象包括资源 ID 和位置等值。

返回值

资源集合的数组。 每种资源类型返回 reference 函数的不同属性。 另外,返回的值因 'Full' 参数的值而异。 有关详细信息,请参阅 reference

references 的输出顺序始终根据复制索引按升序排列。 因此,首先显示集合中索引为 0 的第一个资源,然后显示索引 1,依次显示。 例如,[worker-0, worker-1, worker-2, ...]。

在前面的示例中,如果 worker-0 和 worker-2 已部署,worker-1 未部署,不是由于错误条件,则 references 的输出将省略未部署的资源,并显示已部署的资源(按其编号排序)。 references 的输出将为 [worker-0, worker-2, ...]。如果省略所有资源,则该函数将返回一个空数组。

有效使用

函数 references 不能在资源复制循环Bicep for 循环中使用。 例如,references 在以下方案中不允许使用:

{
  resources: {
    "resourceCollection": {
       "copy": { ... },
       "properties": {
         "prop": "[references(...)]"
       }
    }
  }
}

若要在嵌套模板的输出部分中使用 references 函数或任何 list* 函数,必须将 expressionEvaluationOptions 设置为使用内层作用域计算或使用链接的而不是嵌套的模板。

隐式依赖项

引用 references 函数就是在隐式声明一个资源依赖于另一个资源。 也不需要同时使用 dependsOn 属性。 只有当引用的资源已完成部署后,才会对函数求值。

Reference 示例

以下示例部署一个资源集合,并引用该资源集合。

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "languageVersion": "2.0",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "location": {
      "type": "string",
      "defaultValue": "[resourceGroup().location]",
      "metadata": {
        "description": "Location for all resources."
      }
    },
    "numWorkers": {
      "type": "int",
      "defaultValue": 4,
      "metadata": {
        "description": "The number of workers"
      }
    }
  },
  "resources": {
    "containerWorkers": {
      "copy": {
        "name": "containerWorkers",
        "count": "[length(range(0, parameters('numWorkers')))]"
      },
      "type": "Microsoft.ContainerInstance/containerGroups",
      "apiVersion": "2023-05-01",
      "name": "[format('worker-{0}', range(0, parameters('numWorkers'))[copyIndex()])]",
      "location": "[parameters('location')]",
      "properties": {
        "containers": [
          {
            "name": "[format('worker-container-{0}', range(0, parameters('numWorkers'))[copyIndex()])]",
            "properties": {
              "image": "mcr.microsoft.com/azuredocs/aci-helloworld",
              "ports": [
                {
                  "port": 80,
                  "protocol": "TCP"
                }
              ],
              "resources": {
                "requests": {
                  "cpu": 1,
                  "memoryInGB": 2
                }
              }
            }
          }
        ],
        "osType": "Linux",
        "restartPolicy": "Always",
        "ipAddress": {
          "type": "Public",
          "ports": [
            {
              "port": 80,
              "protocol": "TCP"
            }
          ]
        }
      }
    },
    "containerController": {
      "type": "Microsoft.ContainerInstance/containerGroups",
      "apiVersion": "2023-05-01",
      "name": "controller",
      "location": "[parameters('location')]",
      "properties": {
        "containers": [
          {
            "name": "controller-container",
            "properties": {
              "command": [
                "echo",
                "[format('Worker IPs are {0}', join(map(references('containerWorkers', 'full'), lambda('w', lambdaVariables('w').properties.ipAddress.ip)), ','))]"
              ],
              "image": "mcr.microsoft.com/azuredocs/aci-helloworld",
              "ports": [
                {
                  "port": 80,
                  "protocol": "TCP"
                }
              ],
              "resources": {
                "requests": {
                  "cpu": 1,
                  "memoryInGB": 2
                }
              }
            }
          }
        ],
        "osType": "Linux",
        "restartPolicy": "Always",
        "ipAddress": {
          "type": "Public",
          "ports": [
            {
              "port": 80,
              "protocol": "TCP"
            }
          ]
        }
      },
      "dependsOn": [
        "containerWorkers"
      ]
    }
  },
  "outputs": {
    "workerIpAddresses": {
      "type": "string",
      "value": "[join(map(references('containerWorkers', 'full'), lambda('w', lambdaVariables('w').properties.ipAddress.ip)), ',')]"
    },
    "containersFull": {
      "type": "array",
      "value": "[references('containerWorkers', 'full')]"
    },
    "container": {
      "type": "array",
      "value": "[references('containerWorkers')]"
    }
  }
}

上面的示例返回三个对象。

"outputs": {
  "workerIpAddresses": {
    "type": "String",
    "value": "20.66.74.26,20.245.100.10,13.91.86.58,40.83.249.30"
  },
  "containersFull": {
    "type": "Array",
    "value": [
      {
        "apiVersion": "2023-05-01",
        "condition": true,
        "copyContext": {
          "copyIndex": 0,
          "copyIndexes": {
            "": 0,
            "containerWorkers": 0
          },
          "name": "containerWorkers"
        },
        "copyLoopSymbolicName": "containerWorkers",
        "deploymentResourceLineInfo": {
          "lineNumber": 30,
          "linePosition": 25
        },
        "existing": false,
        "isAction": false,
        "isConditionTrue": true,
        "isTemplateResource": true,
        "location": "westus",
        "properties": {
          "containers": [
            {
              "name": "worker-container-0",
              "properties": {
                "environmentVariables": [],
                "image": "mcr.microsoft.com/azuredocs/aci-helloworld",
                "instanceView": {
                  "currentState": {
                    "detailStatus": "",
                    "startTime": "2023-07-31T19:25:31.996Z",
                    "state": "Running"
                  },
                  "restartCount": 0
                },
                "ports": [
                  {
                    "port": 80,
                    "protocol": "TCP"
                  }
                ],
                "resources": {
                  "requests": {
                    "cpu": 1.0,
                    "memoryInGB": 2.0
                  }
                }
              }
            }
          ],
          "initContainers": [],
          "instanceView": {
            "events": [],
            "state": "Running"
          },
          "ipAddress": {
            "ip": "20.66.74.26",
            "ports": [
              {
                "port": 80,
                "protocol": "TCP"
              }
            ],
            "type": "Public"
          },
          "isCustomProvisioningTimeout": false,
          "osType": "Linux",
          "provisioningState": "Succeeded",
          "provisioningTimeoutInSeconds": 1800,
          "restartPolicy": "Always",
          "sku": "Standard"
        },
        "provisioningOperation": "Create",
        "references": [],
        "resourceGroupName": "demoRg",
        "resourceId": "Microsoft.ContainerInstance/containerGroups/worker-0",
        "scope": "",
        "subscriptionId": "",
        "symbolicName": "containerWorkers[0]"
      },
      ...
    ]
  },
  "containers": {
    "type": "Array",
    "value": [
      {
        "containers": [
          {
            "name": "worker-container-0",
            "properties": {
              "environmentVariables": [],
              "image": "mcr.microsoft.com/azuredocs/aci-helloworld",
              "instanceView": {
                "currentState": {
                  "detailStatus": "",
                  "startTime": "2023-07-31T19:25:31.996Z",
                  "state": "Running"
                },
                "restartCount": 0
              },
              "ports": [
                {
                  "port": 80,
                  "protocol": "TCP"
                }
              ],
              "resources": {
                "requests": {
                  "cpu": 1.0,
                  "memoryInGB": 2.0
                }
              }
            }
          }
        ],
        "initContainers": [],
        "instanceView": {
          "events": [],
          "state": "Running"
        },
        "ipAddress": {
          "ip": "20.66.74.26",
          "ports": [
            {
              "port": 80,
              "protocol": "TCP"
            }
          ],
          "type": "Public"
        },
        "isCustomProvisioningTimeout": false,
        "osType": "Linux",
        "provisioningState": "Succeeded",
        "provisioningTimeoutInSeconds": 1800,
        "restartPolicy": "Always",
        "sku": "Standard"
      },
      ...
    ]
  }
}

resourceGroup

请参阅 resourceGroup 范围函数

在 Bicep 中,使用 resourcegroup 范围函数。

ResourceId

resourceId([subscriptionId], [resourceGroupName], resourceType, resourceName1, [resourceName2], ...)

返回资源的唯一标识符。 如果资源名称不确定或未设置在相同的模板内,请使用此函数。 返回的标识符的格式因部署是在资源组、订阅、管理组还是租户的范围内进行而不同。

在 Bicep 中,使用 resourceId 函数。

parameters

参数 必选 类型​​ 说明
subscriptionId 字符串(GUID 格式) 默认值为当前订阅。 如果需要检索另一个订阅中的资源,请指定此值。 仅在资源组或订阅的范围内部署时才提供此值。
resourceGroupName 字符串 默认值为当前资源组。 如果需要检索另一个资源组中的资源,请指定此值。 仅在资源组的范围内部署时才提供此值。
resourceType 字符串 资源类型,包括资源提供程序命名空间。
resourceName1 字符串 资源的名称。
resourceName2 字符串 下一个资源名称段(如果需要)。

如果资源类型包含更多段,则继续添加资源名称作为参数。

返回值

资源 ID 以不同范围的不同格式返回:

  • 资源组范围:

    /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}
    
  • 订阅范围:

    /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}
    
  • 管理组或租户范围:

    /providers/{resourceProviderNamespace}/{resourceType}/{resourceName}
    

为避免混淆,建议你在使用部署到订阅、管理组或租户的资源时不使用 resourceId。 而改用针对范围设计的 ID 函数。

备注

提供的参数数目各不相同,具体取决于资源是父资源还是子资源,以及资源是否位于同一订阅或资源组中。

若要获取同一订阅和资源组中父资源的资源 ID,请提供资源的类型和名称。

"[resourceId('Microsoft.ServiceBus/namespaces', 'namespace1')]"

若要获取子资源的资源 ID,请注意资源类型中段的数目。 请提供资源类型的每个段的资源名称。 段的名称对应于针对层次结构的该部分存在的资源。

"[resourceId('Microsoft.ServiceBus/namespaces/queues/authorizationRules', 'namespace1', 'queue1', 'auth1')]"

对于属于同一订阅但属于不同资源组的资源,若要获取其资源 ID,请提供资源组名称。

"[resourceId('otherResourceGroup', 'Microsoft.Storage/storageAccounts', 'examplestorage')]"

若要获取位于不同订阅和资源组中的资源的资源 ID,请提供订阅 ID 和资源组名称。

"[resourceId('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', 'otherResourceGroup', 'Microsoft.Storage/storageAccounts','examplestorage')]"

通常,在替代资源组中使用存储帐户或虚拟网络时,需要使用此函数。 以下示例演示了如何轻松使用外部资源组中的资源:

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "location": {
      "type": "string"
    },
    "virtualNetworkName": {
      "type": "string"
    },
    "virtualNetworkResourceGroup": {
      "type": "string"
    },
    "subnet1Name": {
      "type": "string"
    },
    "nicName": {
      "type": "string"
    }
  },
  "variables": {
    "subnet1Ref": "[resourceId(parameters('virtualNetworkResourceGroup'), 'Microsoft.Network/virtualNetworks/subnets', parameters('virtualNetworkName'), parameters('subnet1Name'))]"
  },
  "resources": [
    {
      "type": "Microsoft.Network/networkInterfaces",
      "apiVersion": "2022-11-01",
      "name": "[parameters('nicName')]",
      "location": "[parameters('location')]",
      "properties": {
        "ipConfigurations": [
          {
            "name": "ipconfig1",
            "properties": {
              "privateIPAllocationMethod": "Dynamic",
              "subnet": {
                "id": "[variables('subnet1Ref')]"
              }
            }
          }
        ]
      }
    }
  ]
}

资源 ID 示例

以下示例返回资源组中存储帐户的资源 ID:

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "resources": [],
  "outputs": {
    "sameRGOutput": {
      "type": "string",
      "value": "[resourceId('Microsoft.Storage/storageAccounts','examplestorage')]"
    },
    "differentRGOutput": {
      "type": "string",
      "value": "[resourceId('otherResourceGroup', 'Microsoft.Storage/storageAccounts','examplestorage')]"
    },
    "differentSubOutput": {
      "type": "string",
      "value": "[resourceId('11111111-1111-1111-1111-111111111111', 'otherResourceGroup', 'Microsoft.Storage/storageAccounts','examplestorage')]"
    },
    "nestedResourceOutput": {
      "type": "string",
      "value": "[resourceId('Microsoft.SQL/servers/databases', 'serverName', 'databaseName')]"
    }
  }
}

上述示例中使用默认值的输出为:

名称 类型
sameRGOutput 字符串 /subscriptions/{current-sub-id}/resourceGroups/examplegroup/providers/Microsoft.Storage/storageAccounts/examplestorage
differentRGOutput 字符串 /subscriptions/{current-sub-id}/resourceGroups/otherResourceGroup/providers/Microsoft.Storage/storageAccounts/examplestorage
differentSubOutput 字符串 /subscriptions/11111111-1111-1111-1111-111111111111/resourceGroups/otherResourceGroup/providers/Microsoft.Storage/storageAccounts/examplestorage
nestedResourceOutput 字符串 /subscriptions/{current-sub-id}/resourceGroups/examplegroup/providers/Microsoft.SQL/servers/serverName/databases/databaseName

订阅

请参阅订阅范围函数

在 Bicep 中,使用 subscription 范围函数。

subscriptionResourceId

subscriptionResourceId([subscriptionId], resourceType, resourceName1, [resourceName2], ...)

返回在订阅级别部署的资源的唯一标识符。

在 Bicep 中,使用 subscriptionResourceId 函数。

parameters

参数 必选 类型​​ 说明
subscriptionId 字符串(GUID 格式) 默认值为当前订阅。 如果需要检索另一个订阅中的资源,请指定此值。
resourceType 字符串 资源类型,包括资源提供程序命名空间。
resourceName1 字符串 资源的名称。
resourceName2 字符串 下一个资源名称段(如果需要)。

如果资源类型包含更多段,则继续添加资源名称作为参数。

返回值

使用以下格式返回标识符:

/subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}

备注

我们使用此函数获取部署到订阅而不是资源组的资源的资源 ID。 返回的 ID 不同于 resourceId 函数返回的值,区别在于不包含资源组值。

subscriptionResourceID 示例

以下模板分配内置角色。 可以将它部署到资源组或订阅。 它使用 subscriptionResourceId 函数获取内置角色的资源 ID。

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "principalId": {
      "type": "string",
      "metadata": {
        "description": "The principal to assign the role to"
      }
    },
    "builtInRoleType": {
      "type": "string",
      "allowedValues": [
        "Owner",
        "Contributor",
        "Reader"
      ],
      "metadata": {
        "description": "Built-in role to assign"
      }
    },
    "roleNameGuid": {
      "type": "string",
      "defaultValue": "[newGuid()]",
      "metadata": {
        "description": "A new GUID used to identify the role assignment"
      }
    }
  },
  "variables": {
    "Owner": "[subscriptionResourceId('Microsoft.Authorization/roleDefinitions', '8e3af657-a8ff-443c-a75c-2fe8c4bcb635')]",
    "Contributor": "[subscriptionResourceId('Microsoft.Authorization/roleDefinitions', 'b24988ac-6180-42a0-ab88-20f7382dd24c')]",
    "Reader": "[subscriptionResourceId('Microsoft.Authorization/roleDefinitions', 'acdd72a7-3385-48ef-bd42-f606fba81ae7')]"
  },
  "resources": [
    {
      "type": "Microsoft.Authorization/roleAssignments",
      "apiVersion": "2022-04-01",
      "name": "[parameters('roleNameGuid')]",
      "properties": {
        "roleDefinitionId": "[variables(parameters('builtInRoleType'))]",
        "principalId": "[parameters('principalId')]"
      }
    }
  ]
}

managementGroupResourceId

managementGroupResourceId([managementGroupResourceId],resourceType, resourceName1, [resourceName2], ...)

返回在管理组级别部署的资源的唯一标识符。

在 Bicep 中,使用 managementGroupResourceId 函数。

parameters

参数 必选 类型​​ 说明
managementGroupResourceId 字符串(GUID 格式) 默认值是当前管理组。 如果需要检索另一个管理组中的资源,请指定此值。
resourceType 字符串 资源类型,包括资源提供程序命名空间。
resourceName1 字符串 资源的名称。
resourceName2 字符串 下一个资源名称段(如果需要)。

如果资源类型包含更多段,则继续添加资源名称作为参数。

返回值

使用以下格式返回标识符:

/providers/Microsoft.Management/managementGroups/{managementGroupName}/providers/{resourceType}/{resourceName}

备注

使用此函数可获取部署到管理组而不是资源组的资源的资源 ID。 该函数返回的 ID 不同于 resourceId 函数返回的值,前者不包含订阅 ID 和资源组值。

managementGroupResourceID 示例

以下模板创建并分配策略定义。 它使用 managementGroupResourceId 函数获取策略定义的资源 ID。

{
  "$schema": "https://schema.management.azure.com/schemas/2019-08-01/managementGroupDeploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "targetMG": {
      "type": "string",
      "metadata": {
        "description": "Target Management Group"
      }
    },
    "allowedLocations": {
      "type": "array",
      "defaultValue": [
        "chinaeast",
        "chinanorth",
        "chinanorth2"
      ],
      "metadata": {
        "description": "An array of the allowed locations, all other locations will be denied by the created policy."
      }
    }
  },
  "variables": {
    "mgScope": "[tenantResourceId('Microsoft.Management/managementGroups', parameters('targetMG'))]",
    "policyDefinitionName": "LocationRestriction"
  },
  "resources": [
    {
      "type": "Microsoft.Authorization/policyDefinitions",
      "apiVersion": "2021-06-01",
      "name": "[variables('policyDefinitionName')]",
      "properties": {
        "policyType": "Custom",
        "mode": "All",
        "parameters": {},
        "policyRule": {
          "if": {
            "not": {
              "field": "location",
              "in": "[parameters('allowedLocations')]"
            }
          },
          "then": {
            "effect": "deny"
          }
        }
      }
    },
    "location_lock": {
      "type": "Microsoft.Authorization/policyAssignments",
      "apiVersion": "2022-06-01",
      "name": "location-lock",
      "properties": {
        "scope": "[variables('mgScope')]",
        "policyDefinitionId": "[managementGroupResourceId('Microsoft.Authorization/policyDefinitions', variables('policyDefinitionName'))]"
      },
      "dependsOn": [
        "[format('Microsoft.Authorization/policyDefinitions/{0}', variables('policyDefinitionName'))]"
      ]
    }
  ]
}

tenantResourceId

tenantResourceId(resourceType, resourceName1, [resourceName2], ...)

返回在租户级别部署的资源的唯一标识符。

在 Bicep 中,使用 tenantResourceId 函数。

parameters

参数 必选 类型​​ 说明
resourceType 字符串 资源类型,包括资源提供程序命名空间。
resourceName1 字符串 资源的名称。
resourceName2 字符串 下一个资源名称段(如果需要)。

如果资源类型包含更多段,则继续添加资源名称作为参数。

返回值

使用以下格式返回标识符:

/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}

备注

我们使用此函数获取部署到租户的资源的资源 ID。 返回的 ID 不同于其他资源 ID 函数返回的值,区别在于不包含资源组值或订阅值。

tenantResourceId 示例

内置策略定义是租户级别的资源。 若要部署引用内置策略定义的策略分配,请使用 tenantResourceId 函数。

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "policyDefinitionID": {
      "type": "string",
      "defaultValue": "0a914e76-4921-4c19-b460-a2d36003525a",
      "metadata": {
        "description": "Specifies the ID of the policy definition or policy set definition being assigned."
      }
    },
    "policyAssignmentName": {
      "type": "string",
      "defaultValue": "[guid(parameters('policyDefinitionID'), resourceGroup().name)]",
      "metadata": {
        "description": "Specifies the name of the policy assignment, can be used defined or an idempotent name as the defaultValue provides."
      }
    }
  },
  "resources": [
    {
      "type": "Microsoft.Authorization/policyAssignments",
      "name": "[parameters('policyAssignmentName')]",
      "apiVersion": "2022-06-01",
      "properties": {
        "scope": "[subscriptionResourceId('Microsoft.Resources/resourceGroups', resourceGroup().name)]",
        "policyDefinitionId": "[tenantResourceId('Microsoft.Authorization/policyDefinitions', parameters('policyDefinitionID'))]"
      }
    }
  ]
}

后续步骤