ARM 模板的资源函数Resource functions for ARM templates

资源管理器提供了以下函数,用于获取 Azure 资源管理器 (ARM) 模板中的资源值:Resource Manager provides the following functions for getting resource values in your Azure Resource Manager (ARM) template:

若要从参数、变量或当前部署获取值,请参阅 Deployment value functions(部署值函数)。To get values from parameters, variables, or the current deployment, see Deployment value functions.

extensionResourceIdextensionResourceId

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

返回某个扩展资源的资源 ID,该资源属于适用于其他资源的资源类型,是对其功能的补充。Returns the resource ID for an extension resource, which is a resource type that is applied to another resource to add to its capabilities.

parametersParameters

参数Parameter 必须Required 类型Type 说明Description
ResourceIdresourceId Yes stringstring 扩展资源应用到的资源的资源 ID。The resource ID for the resource that the extension resource is applied to.
resourceTyperesourceType Yes stringstring 资源类型,包括资源提供程序命名空间。Type of resource including resource provider namespace.
resourceName1resourceName1 Yes stringstring 资源的名称。Name of resource.
resourceName2resourceName2 No stringstring 下一个资源名称段(如果需要)。Next resource name segment, if needed.

如果资源类型包含更多段,则继续添加资源名称作为参数。Continue adding resource names as parameters when the resource type includes more segments.

返回值Return value

此函数返回的资源 ID 的基本格式为:The basic format of the resource ID returned by this function is:

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

作用域段因扩展的资源而异。The scope segment varies by the resource being extended.

当扩展资源应用到某个资源时,资源 ID 以下述格式返回:When the extension resource is applied to a resource, the resource ID is returned in the following format:

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

当扩展资源应用到某个资源组时,格式为:When the extension resource is applied to a resource group, the format is:

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

当扩展资源应用到某个订阅时,格式为:When the extension resource is applied to a subscription, the format is:

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

当扩展资源应用到某个管理组时,格式为:When the extension resource is applied to a management group, the format is:

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

extensionResourceId 示例extensionResourceId example

以下示例返回资源组锁的资源 ID。The following example returns the resource ID for a resource group lock.

{
    "$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'))]"
        }
    }
}

部署到管理组的自定义策略定义是作为扩展资源实现的。A custom policy definition deployed to a management group is implemented as an extension resource. 若要创建和分配策略,请将以下模板部署到管理组。To create and assign a policy, deploy the following template to a management group.

{
    "$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": [
                "chinaeast2",
                "australiasoutheast",
                "australiacentral"
            ],
            "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'))]",
        "policyDefinition": "LocationRestriction"
    },
    "resources": [
        {
            "type": "Microsoft.Authorization/policyDefinitions",
            "name": "[variables('policyDefinition')]",
            "apiVersion": "2019-09-01",
            "properties": {
                "policyType": "Custom",
                "mode": "All",
                "parameters": {
                },
                "policyRule": {
                    "if": {
                        "not": {
                            "field": "location",
                            "in": "[parameters('allowedLocations')]"
                        }
                    },
                    "then": {
                        "effect": "deny"
                    }
                }
            }
        },
        {
            "type": "Microsoft.Authorization/policyAssignments",
            "name": "location-lock",
            "apiVersion": "2019-09-01",
            "dependsOn": [
                "[variables('policyDefinition')]"
            ],
            "properties": {
                "scope": "[variables('mgScope')]",
                "policyDefinitionId": "[extensionResourceId(variables('mgScope'), 'Microsoft.Authorization/policyDefinitions', variables('policyDefinition'))]"
            }
        }
    ]
}

内置策略定义是租户级别的资源。Built-in policy definitions are tenant level resources. 有关部署内置策略定义的示例,请参阅 tenantResourceIdFor an example of deploying a built-in policy definition, see tenantResourceId.

list*list*

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

此函数的语法因列表操作的名称而异。The syntax for this function varies by name of the list operations. 每个实现都为支持列表操作的资源类型返回值。Each implementation returns values for the resource type that supports a list operation. 操作名称必须以 list 开头。The operation name must start with list. 一些常见用法是 listKeyslistKeyValuelistSecretsSome common usages are listKeys, listKeyValue, and listSecrets.

parametersParameters

参数Parameter 必需Required 类型Type 说明Description
resourceName 或 resourceIdentifierresourceName or resourceIdentifier Yes stringstring 资源的唯一标识符。Unique identifier for the resource.
apiVersionapiVersion Yes 字符串string 资源运行时状态的 API 版本。API version of resource runtime state. 通常采用 yyyy-mm-dd格式。Typically, in the format, yyyy-mm-dd.
functionValuesfunctionValues No objectobject 具有函数值的对象。An object that has values for the function. 仅为支持接收具有参数值的对象的函数提供此对象,例如存储帐户上的 listAccountSas。Only provide this object for functions that support receiving an object with parameter values, such as listAccountSas on a storage account. 本文中演示了传递函数值的示例。An example of passing function values is shown in this article.

有效使用Valid uses

列表函数可以在资源定义的属性中使用。The list functions can be used in the properties of a resource definition. 请勿使用在模板的 outputs 节中公开敏感信息的列表函数。Don't use a list function that exposes sensitive information in the outputs section of a template. 输出值存储在部署历史记录中,可能会被恶意用户检索到。Output values are stored in the deployment history and could be retrieved by a malicious user.

属性迭代一起使用时,可以使用 input 的 list 函数,因为表达式已分配给资源属性。When used with property iteration, you can use the list functions for input because the expression is assigned to the resource property. 不能将它们与 count 一起使用,因为必须在解析 list 函数之前确定计数。You can't use them with count because the count must be determined before the list function is resolved.

实现形式Implementations

下表中显示 list* 的可能用途。The possible uses of list* are shown in the following table.

资源类型Resource type 函数名称Function name
Microsoft.AnalysisServices/serversMicrosoft.AnalysisServices/servers listGatewayStatuslistGatewayStatus
Microsoft.ApiManagement/service/authorizationServersMicrosoft.ApiManagement/service/authorizationServers listSecretslistSecrets
Microsoft.ApiManagement/service/gatewaysMicrosoft.ApiManagement/service/gateways listKeyslistKeys
Microsoft.ApiManagement/service/identityProvidersMicrosoft.ApiManagement/service/identityProviders listSecretslistSecrets
Microsoft.ApiManagement/service/namedValuesMicrosoft.ApiManagement/service/namedValues listValuelistValue
Microsoft.ApiManagement/service/openidConnectProvidersMicrosoft.ApiManagement/service/openidConnectProviders listSecretslistSecrets
Microsoft.Automation/automationAccountsMicrosoft.Automation/automationAccounts listKeyslistKeys
Microsoft.Batch/batchAccountsMicrosoft.Batch/batchAccounts listkeyslistkeys
Microsoft.Cache/redisMicrosoft.Cache/redis listKeyslistKeys
Microsoft.CognitiveServices/accountsMicrosoft.CognitiveServices/accounts listKeyslistKeys
Microsoft.ContainerRegistry/registriesMicrosoft.ContainerRegistry/registries listBuildSourceUploadUrllistBuildSourceUploadUrl
Microsoft.ContainerRegistry/registriesMicrosoft.ContainerRegistry/registries listCredentialslistCredentials
Microsoft.ContainerRegistry/registriesMicrosoft.ContainerRegistry/registries listUsageslistUsages
Microsoft.ContainerRegistry/registries/agentpoolsMicrosoft.ContainerRegistry/registries/agentpools listQueueStatuslistQueueStatus
Microsoft.ContainerRegistry/registries/buildTasksMicrosoft.ContainerRegistry/registries/buildTasks listSourceRepositoryPropertieslistSourceRepositoryProperties
Microsoft.ContainerRegistry/registries/buildTasks/stepsMicrosoft.ContainerRegistry/registries/buildTasks/steps listBuildArgumentslistBuildArguments
Microsoft.ContainerRegistry/registries/taskrunsMicrosoft.ContainerRegistry/registries/taskruns listDetailslistDetails
Microsoft.ContainerRegistry/registries/webhooksMicrosoft.ContainerRegistry/registries/webhooks listEventslistEvents
Microsoft.ContainerRegistry/registries/runsMicrosoft.ContainerRegistry/registries/runs listLogSasUrllistLogSasUrl
Microsoft.ContainerRegistry/registries/tasksMicrosoft.ContainerRegistry/registries/tasks listDetailslistDetails
Microsoft.ContainerService/managedClustersMicrosoft.ContainerService/managedClusters listClusterAdminCredentiallistClusterAdminCredential
Microsoft.ContainerService/managedClustersMicrosoft.ContainerService/managedClusters listClusterMonitoringUserCredentiallistClusterMonitoringUserCredential
Microsoft.ContainerService/managedClustersMicrosoft.ContainerService/managedClusters listClusterUserCredentiallistClusterUserCredential
Microsoft.ContainerService/managedClusters/accessProfilesMicrosoft.ContainerService/managedClusters/accessProfiles listCredentiallistCredential
Microsoft.DataBox/jobsMicrosoft.DataBox/jobs listCredentialslistCredentials
Microsoft.DataFactory/datafactories/gatewaysMicrosoft.DataFactory/datafactories/gateways listauthkeyslistauthkeys
Microsoft.DataFactory/factories/integrationruntimesMicrosoft.DataFactory/factories/integrationruntimes listauthkeyslistauthkeys
Microsoft.Devices/iotHubsMicrosoft.Devices/iotHubs listkeyslistkeys
Microsoft.Devices/iotHubs/iotHubKeysMicrosoft.Devices/iotHubs/iotHubKeys listkeyslistkeys
Microsoft.Devices/provisioningServices/keysMicrosoft.Devices/provisioningServices/keys listkeyslistkeys
Microsoft.Devices/provisioningServicesMicrosoft.Devices/provisioningServices listkeyslistkeys
Microsoft.DocumentDB/databaseAccountsMicrosoft.DocumentDB/databaseAccounts listConnectionStringslistConnectionStrings
Microsoft.DocumentDB/databaseAccountsMicrosoft.DocumentDB/databaseAccounts listKeyslistKeys
Microsoft.DocumentDB/databaseAccounts/notebookWorkspacesMicrosoft.DocumentDB/databaseAccounts/notebookWorkspaces listConnectionInfolistConnectionInfo
Microsoft.DomainRegistrationMicrosoft.DomainRegistration listDomainRecommendationslistDomainRecommendations
Microsoft.DomainRegistration/topLevelDomainsMicrosoft.DomainRegistration/topLevelDomains listAgreementslistAgreements
Microsoft.EventGrid/domainsMicrosoft.EventGrid/domains listKeyslistKeys
Microsoft.EventGrid/topicsMicrosoft.EventGrid/topics listKeyslistKeys
Microsoft.EventHub/namespaces/authorizationRulesMicrosoft.EventHub/namespaces/authorizationRules listkeyslistkeys
Microsoft.EventHub/namespaces/disasterRecoveryConfigs/authorizationRulesMicrosoft.EventHub/namespaces/disasterRecoveryConfigs/authorizationRules listkeyslistkeys
Microsoft.EventHub/namespaces/eventhubs/authorizationRulesMicrosoft.EventHub/namespaces/eventhubs/authorizationRules listkeyslistkeys
Microsoft.ImportExport/jobsMicrosoft.ImportExport/jobs listBitLockerKeyslistBitLockerKeys
Microsoft.Kusto/Clusters/DatabasesMicrosoft.Kusto/Clusters/Databases ListPrincipalsListPrincipals
Microsoft.Logic/integrationAccounts/agreementsMicrosoft.Logic/integrationAccounts/agreements listContentCallbackUrllistContentCallbackUrl
Microsoft.Logic/integrationAccounts/assembliesMicrosoft.Logic/integrationAccounts/assemblies listContentCallbackUrllistContentCallbackUrl
Microsoft.Logic/integrationAccountsMicrosoft.Logic/integrationAccounts listCallbackUrllistCallbackUrl
Microsoft.Logic/integrationAccountsMicrosoft.Logic/integrationAccounts listKeyVaultKeyslistKeyVaultKeys
Microsoft.Logic/integrationAccounts/mapsMicrosoft.Logic/integrationAccounts/maps listContentCallbackUrllistContentCallbackUrl
Microsoft.Logic/integrationAccounts/partnersMicrosoft.Logic/integrationAccounts/partners listContentCallbackUrllistContentCallbackUrl
Microsoft.Logic/integrationAccounts/schemasMicrosoft.Logic/integrationAccounts/schemas listContentCallbackUrllistContentCallbackUrl
Microsoft.Logic/workflowsMicrosoft.Logic/workflows listCallbackUrllistCallbackUrl
Microsoft.Logic/workflowsMicrosoft.Logic/workflows listSwaggerlistSwagger
Microsoft.Logic/workflows/runs/actionsMicrosoft.Logic/workflows/runs/actions listExpressionTraceslistExpressionTraces
Microsoft.Logic/workflows/runs/actions/repetitionsMicrosoft.Logic/workflows/runs/actions/repetitions listExpressionTraceslistExpressionTraces
Microsoft.Logic/workflows/triggersMicrosoft.Logic/workflows/triggers listCallbackUrllistCallbackUrl
Microsoft.Logic/workflows/versions/triggersMicrosoft.Logic/workflows/versions/triggers listCallbackUrllistCallbackUrl
Microsoft.MachineLearning/webServicesMicrosoft.MachineLearning/webServices listkeyslistkeys
Microsoft.MachineLearningServices/workspaces/computesMicrosoft.MachineLearningServices/workspaces/computes listKeyslistKeys
Microsoft.MachineLearningServices/workspaces/computesMicrosoft.MachineLearningServices/workspaces/computes listNodeslistNodes
Microsoft.MachineLearningServices/workspacesMicrosoft.MachineLearningServices/workspaces listKeyslistKeys
Microsoft.Media/mediaservices/assetsMicrosoft.Media/mediaservices/assets listContainerSaslistContainerSas
Microsoft.Media/mediaservices/assetsMicrosoft.Media/mediaservices/assets listStreamingLocatorslistStreamingLocators
Microsoft.Media/mediaservices/streamingLocatorsMicrosoft.Media/mediaservices/streamingLocators listContentKeyslistContentKeys
Microsoft.Media/mediaservices/streamingLocatorsMicrosoft.Media/mediaservices/streamingLocators listPathslistPaths
Microsoft.Network/applicationSecurityGroupsMicrosoft.Network/applicationSecurityGroups listIpConfigurationslistIpConfigurations
Microsoft.NotificationHubs/Namespaces/authorizationRulesMicrosoft.NotificationHubs/Namespaces/authorizationRules listkeyslistkeys
Microsoft.NotificationHubs/Namespaces/NotificationHubs/authorizationRulesMicrosoft.NotificationHubs/Namespaces/NotificationHubs/authorizationRules listkeyslistkeys
Microsoft.OperationalInsights/workspacesMicrosoft.OperationalInsights/workspaces listlist
Microsoft.OperationalInsights/workspacesMicrosoft.OperationalInsights/workspaces listKeyslistKeys
Microsoft.PolicyInsights/remediationsMicrosoft.PolicyInsights/remediations listDeploymentslistDeployments
Microsoft.Relay/namespaces/authorizationRulesMicrosoft.Relay/namespaces/authorizationRules listkeyslistkeys
Microsoft.Relay/namespaces/disasterRecoveryConfigs/authorizationRulesMicrosoft.Relay/namespaces/disasterRecoveryConfigs/authorizationRules listkeyslistkeys
Microsoft.Relay/namespaces/HybridConnections/authorizationRulesMicrosoft.Relay/namespaces/HybridConnections/authorizationRules listkeyslistkeys
Microsoft.Relay/namespaces/WcfRelays/authorizationRulesMicrosoft.Relay/namespaces/WcfRelays/authorizationRules listkeyslistkeys
Microsoft.Search/searchServicesMicrosoft.Search/searchServices listAdminKeyslistAdminKeys
Microsoft.Search/searchServicesMicrosoft.Search/searchServices listQueryKeyslistQueryKeys
Microsoft.ServiceBus/namespaces/authorizationRulesMicrosoft.ServiceBus/namespaces/authorizationRules listkeyslistkeys
Microsoft.ServiceBus/namespaces/disasterRecoveryConfigs/authorizationRulesMicrosoft.ServiceBus/namespaces/disasterRecoveryConfigs/authorizationRules listkeyslistkeys
Microsoft.ServiceBus/namespaces/queues/authorizationRulesMicrosoft.ServiceBus/namespaces/queues/authorizationRules listkeyslistkeys
Microsoft.ServiceBus/namespaces/topics/authorizationRulesMicrosoft.ServiceBus/namespaces/topics/authorizationRules
Microsoft.SignalRService/SignalRMicrosoft.SignalRService/SignalR listkeyslistkeys
Microsoft.Storage/storageAccountsMicrosoft.Storage/storageAccounts listAccountSaslistAccountSas
Microsoft.Storage/storageAccountsMicrosoft.Storage/storageAccounts listkeyslistkeys
Microsoft.Storage/storageAccountsMicrosoft.Storage/storageAccounts listServiceSaslistServiceSas
Microsoft.Web/connectionGatewaysMicrosoft.Web/connectionGateways ListStatusListStatus
microsoft.web/connectionsmicrosoft.web/connections listconsentlinkslistconsentlinks
Microsoft.Web/customApisMicrosoft.Web/customApis listWsdlInterfaceslistWsdlInterfaces
microsoft.web/locationsmicrosoft.web/locations listwsdlinterfaceslistwsdlinterfaces
microsoft.web/apimanagementaccounts/apis/connectionsmicrosoft.web/apimanagementaccounts/apis/connections listconnectionkeyslistconnectionkeys
microsoft.web/apimanagementaccounts/apis/connectionsmicrosoft.web/apimanagementaccounts/apis/connections listsecretslistsecrets
microsoft.web/sites/backupsmicrosoft.web/sites/backups listlist
Microsoft.Web/sites/configMicrosoft.Web/sites/config listlist
microsoft.web/sites/functionsmicrosoft.web/sites/functions listkeyslistkeys
microsoft.web/sites/functionsmicrosoft.web/sites/functions listsecretslistsecrets
microsoft.web/sites/hybridconnectionnamespaces/relaysmicrosoft.web/sites/hybridconnectionnamespaces/relays listkeyslistkeys
microsoft.web/sitesmicrosoft.web/sites listsyncfunctiontriggerstatuslistsyncfunctiontriggerstatus
microsoft.web/sites/slots/functionsmicrosoft.web/sites/slots/functions listsecretslistsecrets
microsoft.web/sites/slots/backupsmicrosoft.web/sites/slots/backups listlist
Microsoft.Web/sites/slots/configMicrosoft.Web/sites/slots/config listlist
microsoft.web/sites/slots/functionsmicrosoft.web/sites/slots/functions listsecretslistsecrets

若要确定哪些资源类型具有列表操作,请使用以下选项:To determine which resource types have a list operation, you have the following options:

  • 查看资源提供程序的 REST API 操作,并查找列表操作。View the REST API operations for a resource provider, and look for list operations. 例如,存储帐户具有 listKeys 操作For example, storage accounts have the listKeys operation.

  • 使用 Get-AzProviderOperation PowerShell cmdlet。Use the Get-AzProviderOperation PowerShell cmdlet. 以下示例获取存储帐户的所有列表操作:The following example gets all list operations for storage accounts:

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

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

返回值Return value

返回的对象因使用的列表函数而异。The returned object varies by the list function you use. 例如,用于存储帐户的 listKeys 返回以下格式:For example, the listKeys for a storage account returns the following format:

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

其他列表函数具有不同的返回格式。Other list functions have different return formats. 若要查看函数的格式,请将其包含在 outputs 节中,如示例模板所示。To see the format of a function, include it in the outputs section as shown in the example template.

备注Remarks

使用资源名称或 resourceId 函数来指定资源。Specify the resource by using either the resource name or the resourceId function. 在部署被引用资源的同一模板中使用列表函数时,请使用资源名称。When using a list function in the same template that deploys the referenced resource, use the resource name.

如果在有条件部署的资源中使用 list 函数,则会对该函数进行评估,即使资源尚未部署。If you use a list function in a resource that is conditionally deployed, the function is evaluated even if the resource isn't deployed. 如果 list 函数引用的资源不存在,系统会显示错误。You get an error if the list function refers to a resource that doesn't exist. 使用 if 函数确保仅在部署资源时才评估函数。Use the if function to make sure the function is only evaluated when the resource is being deployed. 请参阅 if 函数以获取使用 if 和 list 以及有条件部署的资源的示例模板。See the if function for a sample template that uses if and list with a conditionally deployed resource.

List 示例List example

以下示例在为部署脚本设置值时使用了 listKeys。The following example uses listKeys when setting a value for deployment scripts.

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

下一个示例演示采用参数的列表函数。The next example shows a list function that takes a parameter. 在本例中,函数为 listAccountSas。In this case, the function is listAccountSas. 请为到期时间传递一个对象。Pass an object for the expiry time. 到期时间必须是将来的时间。The expiry time must be in the future.

"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]"

providersproviders

providers(providerNamespace, [resourceType])

返回有关资源提供程序及其支持的资源类型的信息。Returns information about a resource provider and its supported resource types. 如果未提供资源类型,则该函数将返回资源提供程序支持的所有类型。If you don't provide a resource type, the function returns all the supported types for the resource provider.

参数Parameters

参数Parameter 必需Required 类型Type 说明Description
providerNamespaceproviderNamespace Yes 字符串string 提供程序的命名空间Namespace of the provider
resourceTyperesourceType No 字符串string 指定的命名空间中的资源类型。The type of resource within the specified namespace.

返回值Return value

将使用以下格式返回支持的每个类型:Each supported type is returned in the following format:

{
    "resourceType": "{name of resource type}",
    "locations": [ all supported locations ],
    "apiVersions": [ all supported API versions ]
}

不保证返回值的数组排序。Array ordering of the returned values isn't guaranteed.

Provider 示例Providers example

以下示例模板演示如何使用 provider 函数:The following example template shows how to use the provider function:

{
    "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "providerNamespace": {
            "type": "string"
        },
        "resourceType": {
            "type": "string"
        }
    },
    "resources": [],
    "outputs": {
        "providerOutput": {
            "value": "[providers(parameters('providerNamespace'), parameters('resourceType'))]",
            "type" : "object"
        }
    }
}

对于 Microsoft.Web 资源提供程序和站点资源类型,上面的示例返回以下格式的对象 :For the Microsoft.Web resource provider and sites resource type, the preceding example returns an object in the following format:

{
  "resourceType": "sites",
  "locations": [
    "China East",
    "China North",
    "China East 2",
    "China North 2",
    ...
  ],
  "apiVersions": [
    "2016-08-01",
    "2016-03-01",
    "2015-08-01-preview",
    "2015-08-01",
    ...
  ]
}

referencereference

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

返回表示资源的运行时状态的对象。Returns an object representing a resource's runtime state.

参数Parameters

参数Parameter 必需Required 类型Type 说明Description
resourceName 或 resourceIdentifierresourceName or resourceIdentifier Yes 字符串string 资源的名称或唯一标识符。Name or unique identifier of a resource. 当引用当前模板中的资源时,请仅提供资源名称作为参数。When referencing a resource in the current template, provide only the resource name as a parameter. 当引用以前部署的资源或者资源名称不明确时,请提供资源 ID。When referencing a previously deployed resource or when the name of the resource is ambiguous, provide the resource ID.
apiVersionapiVersion No 字符串string 指定的资源的 API 版本。API version of the specified resource. 如果资源不是在同一模板中预配的,则需要此参数。This parameter is required when the resource isn't provisioned within same template. 通常采用 yyyy-mm-dd格式。Typically, in the format, yyyy-mm-dd.
'Full''Full' No 字符串string 一个值,指定是否要返回完整资源对象。Value that specifies whether to return the full resource object. 如果未指定 'Full',仅返回资源的属性对象。If you don't specify 'Full', only the properties object of the resource is returned. 完整对象包括资源 ID 和位置等值。The full object includes values such as the resource ID and location.

返回值Return value

每种资源类型返回 reference 函数的不同属性。Every resource type returns different properties for the reference function. 该函数不返回单个预定义的格式。The function doesn't return a single, predefined format. 另外,返回的值因 'Full' 参数的值而异。Also, the returned value differs based on the value of the 'Full' argument. 若要查看资源类型的属性,请返回 outputs 节中的对象,如示例所示。To see the properties for a resource type, return the object in the outputs section as shown in the example.

备注Remarks

reference 函数检索以前部署的资源或在当前模板中部署的资源的运行时状态。The reference function retrieves the runtime state of either a previously deployed resource or a resource deployed in the current template. 本文展示了这两种方案的示例。This article shows examples for both scenarios.

通常情况下,可以使用 reference 函数返回对象的特定值,例如 blob 终结点 URI 或完全限定的域名。Typically, you use the reference function to return a particular value from an object, such as the blob endpoint URI or fully qualified domain name.

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

需要不属于属性架构的资源值时,请使用 'Full'Use 'Full' when you need resource values that aren't part of the properties schema. 例如,若要设置密钥保管库访问策略,请获取虚拟机的标识属性。For example, to set key vault access policies, get the identity properties for a virtual machine.

{
  "type": "Microsoft.KeyVault/vaults",
  "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"
          ]
        }
      }
    ],
    ...

有效使用Valid uses

reference 函数只能用在资源定义的 properties 中以及模板或部署的 outputs 节中。The reference function can only be used in the properties of a resource definition and the outputs section of a template or deployment. 属性迭代一起使用时,可以将 reference 函数用于 input,因为该表达式是分配给资源属性的。When used with property iteration, you can use the reference function for input because the expression is assigned to the resource property.

不能使用引用函数在复制循环中设置 count 属性的值。You can't use the reference function to set the value of the count property in a copy loop. 可用于在循环中设置其他属性。You can use to set other properties in the loop. count 属性的引用会被阻止,因为必须在解析引用函数之前确定该属性。Reference is blocked for the count property because that property must be determined before the reference function is resolved.

若要在嵌套模板的输出部分中使用 reference 函数或任何 list* 函数,必须将 expressionEvaluationOptions 设置为使用内层作用域计算或使用链接的而不是嵌套的模板。To use the reference function or any list* function in the outputs section of a nested template, you must set the expressionEvaluationOptions to use inner scope evaluation or use a linked instead of a nested template.

如果在有条件部署的资源中使用 reference 函数,则会对该函数进行评估,即使资源尚未部署。If you use the reference function in a resource that is conditionally deployed, the function is evaluated even if the resource isn't deployed. 如果 reference 函数引用的资源不存在,系统会显示错误。You get an error if the reference function refers to a resource that doesn't exist. 使用 if 函数确保仅在部署资源时才评估函数。Use the if function to make sure the function is only evaluated when the resource is being deployed. 请参阅 if 函数以获取使用 if 和 reference 以及有条件部署的资源的示例模板。See the if function for a sample template that uses if and reference with a conditionally deployed resource.

隐式依赖项Implicit dependency

如果在同一模板内预配了被引用资源且通过其名称(而非资源 ID)引用该资源,则使用 reference 函数会隐式声明一个资源依赖于另一个资源。By using the reference function, you implicitly declare that one resource depends on another resource if the referenced resource is provisioned within same template and you refer to the resource by its name (not resource ID). 也不需要同时使用 dependsOn 属性。You don't need to also use the dependsOn property. 只有当引用的资源已完成部署后,才会对函数求值。The function isn't evaluated until the referenced resource has completed deployment.

资源名称或标识符Resource name or identifier

若要引用在同一模板中部署的资源,请提供资源的名称。When referencing a resource that is deployed in the same template, provide the name of the resource.

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

引用没有部署在同一模板中的资源时,请提供资源 ID 和 apiVersionWhen referencing a resource that isn't deployed in the same template, provide the resource ID and apiVersion.

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

若要避免所引用的资源不明确,可以提供完全限定的资源标识符。To avoid ambiguity about which resource you're referencing, you can provide a fully qualified resource identifier.

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

向资源构造完全限定的引用时,类型和名称的分段组合顺序并不是这两者的简单串联。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}]{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

若要简化任何资源 ID 的创建,请使用本文档中所述的 resourceId() 函数,而不是 concat() 函数。To simplify the creation of any resource ID, use the resourceId() functions described in this document instead of the concat() function.

获取托管标识Get managed identity

Azure 资源的托管标识是为某些资源隐式创建的扩展资源类型Managed identities for Azure resources are extension resource types that are created implicitly for some resources. 由于模板中未显式定义托管标识,因此必须引用该标识所应用到的资源。Because the managed identity isn't explicitly defined in the template, you must reference the resource that the identity is applied to. 使用 Full 获取所有属性,包括隐式创建的标识。Use Full to get all of the properties, including the implicitly created identity.

模式为:The pattern is:

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

例如,若要获取应用于虚拟机的托管标识的主体 ID,请使用:For example, to get the principal ID for a managed identity that is applied to a virtual machine, use:

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

或者,若要获取应用于虚拟机规模集的托管标识的租户 ID,请使用:Or, to get the tenant ID for a managed identity that is applied to a virtual machine scale set, use:

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

Reference 示例Reference example

以下示例模板部署一个资源并引用该资源。The following example template deploys a resource, and references that resource.

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

上面的示例返回两个对象。The preceding example returns the two objects. 属性对象采用以下格式:The properties object is in the following format:

{
   "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": "chinaeast",
   "provisioningState": "Succeeded",
   "statusOfPrimary": "available",
   "supportsHttpsTrafficOnly": false
}

完整对象采用以下格式:The full object is in the following format:

{
  "apiVersion":"2016-12-01",
  "location":"chinaeast",
  "sku": {
    "name":"Standard_LRS",
    "tier":"Standard"
  },
  "tags":{},
  "kind":"Storage",
  "properties": {
    "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":"chinaeast",
    "provisioningState":"Succeeded",
    "statusOfPrimary":"available",
    "supportsHttpsTrafficOnly":false
  },
  "subscriptionId":"<subscription-id>",
  "resourceGroupName":"functionexamplegroup",
  "resourceId":"Microsoft.Storage/storageAccounts/examplestorage",
  "referenceApiVersion":"2016-12-01",
  "condition":true,
  "isConditionTrue":true,
  "isTemplateResource":false,
  "isAction":false,
  "provisioningOperation":"Read"
}

以下示例模板引用的存储帐户未在此模板中部署。The following example template references a storage account that isn't deployed in this template. 同一订阅内已存在该存储帐户。The storage account already exists within the same subscription.

{
    "$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": {
            "value": "[reference(resourceId(parameters('storageResourceGroup'), 'Microsoft.Storage/storageAccounts', parameters('storageAccountName')), '2018-07-01')]",
            "type": "object"
        }
    }
}

resourceGroupresourceGroup

resourceGroup()

返回表示当前资源组的对象。Returns an object that represents the current resource group.

返回值Return value

返回的对象采用以下格式:The returned object is in the following format:

{
  "id": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}",
  "name": "{resourceGroupName}",
  "type":"Microsoft.Resources/resourceGroups",
  "location": "{resourceGroupLocation}",
  "managedBy": "{identifier-of-managing-resource}",
  "tags": {
  },
  "properties": {
    "provisioningState": "{status}"
  }
}

只有在资源组包含的资源由另一服务托管时,才会返回 managedBy 属性。The managedBy property is returned only for resource groups that contain resources that are managed by another service. 对于托管应用程序和 AKS,此属性的值是管理资源的资源 ID。For Managed Applications, and AKS, the value of the property is the resource ID of the managing resource.

备注Remarks

resourceGroup() 函数不能用于在订阅级别部署的模板中。The resourceGroup() function can't be used in a template that is deployed at the subscription level. 它只能用于部署到资源组的模板中。It can only be used in templates that are deployed to a resource group. 可以在以资源组为目标的链接模板或嵌套模板(具有内部范围)中使用 resourceGroup() 函数,即使父模板部署到订阅,也是如此。You can use the resourceGroup() function in a linked or nested template (with inner scope) that targets a resource group, even when the parent template is deployed to the subscription. 在这种情况下,链接模板或嵌套模板将在资源组级别进行部署。In that scenario, the linked or nested template is deployed at the resource group level. 若要详细了解如何在订阅级别部署中将资源组作为目标,请参阅将 Azure 资源部署到多个订阅或资源组For more information about targeting a resource group in a subscription level deployment, see Deploy Azure resources to more than one subscription or resource group.

resourceGroup 函数的一个常见用途是在与资源组相同的位置中创建资源。A common use of the resourceGroup function is to create resources in the same location as the resource group. 以下示例使用资源组位置作为默认参数值。The following example uses the resource group location for a default parameter value.

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

还可以使用 resourceGroup 函数将资源组中的标记应用于资源。You can also use the resourceGroup function to apply tags from the resource group to a resource. 有关详细信息,请参阅应用资源组中的标记For more information, see Apply tags from resource group.

使用嵌套模板部署到多个资源组时,可以指定评估 resourceGroup 函数的范围。When using nested templates to deploy to multiple resource groups, you can specify the scope for evaluating the resourceGroup function. 有关详细信息,将 Azure 资源部署到多个订阅或资源组For more information, see Deploy Azure resources to more than one subscription or resource group.

资源组示例Resource group example

以下示例模板返回资源组的属性。The following example template returns the properties of the resource group.

{
    "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "resources": [],
    "outputs": {
        "resourceGroupOutput": {
            "value": "[resourceGroup()]",
            "type" : "object"
        }
    }
}

上述示例返回采用以下格式的对象:The preceding example returns an object in the following format:

{
  "id": "/subscriptions/{subscription-id}/resourceGroups/examplegroup",
  "name": "examplegroup",
  "type":"Microsoft.Resources/resourceGroups",
  "location": "chinaeast",
  "properties": {
    "provisioningState": "Succeeded"
  }
}

ResourceIdresourceId

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

返回资源的唯一标识符。Returns the unique identifier of a resource. 如果资源名称不确定或未设置在相同的模板内,请使用此函数。You use this function when the resource name is ambiguous or not provisioned within the same template. 返回的标识符的格式因部署是在资源组、订阅、管理组还是租户的范围内进行而不同。The format of the returned identifier varies based on whether the deployment happens at the scope of a resource group, subscription, management group, or tenant.

参数Parameters

参数Parameter 必需Required 类型Type 说明Description
subscriptionIdsubscriptionId No 字符串(GUID 格式)string (In GUID format) 默认值为当前订阅。Default value is the current subscription. 如果需要检索另一个订阅中的资源,请指定此值。Specify this value when you need to retrieve a resource in another subscription. 仅在资源组或订阅的范围内部署时才提供此值。Only provide this value when deploying at the scope of a resource group or subscription.
resourceGroupNameresourceGroupName No 字符串string 默认值为当前资源组。Default value is current resource group. 如果需要检索另一个资源组中的资源,请指定此值。Specify this value when you need to retrieve a resource in another resource group. 仅在资源组的范围内部署时才提供此值。Only provide this value when deploying at the scope of a resource group.
resourceTyperesourceType Yes 字符串string 资源类型,包括资源提供程序命名空间。Type of resource including resource provider namespace.
resourceName1resourceName1 Yes 字符串string 资源的名称。Name of resource.
resourceName2resourceName2 No 字符串string 下一个资源名称段(如果需要)。Next resource name segment, if needed.

如果资源类型包含更多段,则继续添加资源名称作为参数。Continue adding resource names as parameters when the resource type includes more segments.

返回值Return value

在资源组的范围内部署模板时,将以以下格式返回资源 ID:When the template is deployed at the scope of a resource group, the resource ID is returned in the following format:

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

可以对其他部署范围使用 resourceId 函数,但 ID 的格式会发生更改。You can use the resourceId function for other deployment scopes, but the format of the ID changes.

如果在部署到订阅时使用 resourceId,则会按以下格式返回资源 ID:If you use resourceId while deploying to a subscription, the resource ID is returned in the following format:

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

如果在部署到管理组或租户时使用 resourceId,则会按以下格式返回资源 ID:If you use resourceId while deploying to a management group or tenant, the resource ID is returned in the following format:

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

为避免混淆,建议你在使用部署到订阅、管理组或租户的资源时不使用 resourceId,To avoid confusion, we recommend that you not use resourceId when working with resources deployed to the subscription, management group, or tenant. 而改用针对范围设计的 ID 函数。Instead, use the ID function that is designed for the scope.

对于订阅级别的资源,请使用 subscriptionResourceId 函数。For subscription-level resources, use the subscriptionResourceId function.

对于管理组级别的资源,请使用 extensionResourceId 函数来引用作为管理组的扩展实现的资源。For management group-level resources, use the extensionResourceId function to reference a resource that is implemented as an extension of a management group. 例如,部署到管理组的自定义策略定义是管理组的扩展。For example, custom policy definitions that are deployed to a management group are extensions of the management group. 请使用 tenantResourceId 函数来引用已部署到租户但在你的管理组中可用的资源。Use the tenantResourceId function to reference resources that are deployed to the tenant but available in your management group. 例如,内置策略定义是作为租户级别的资源实现的。For example, built-in policy definitions are implemented as tenant level resources.

对于租户级别的资源,请使用 tenantResourceId 函数。For tenant-level resources, use the tenantResourceId function. 请对内置策略定义使用 tenantResourceId,因为内置策略定义是在租户级别实现的。Use tenantResourceId for built-in policy definitions because they are implemented at the tenant level.

备注Remarks

提供的参数数目各不相同,具体取决于资源是父资源还是子资源,以及资源是否位于同一订阅或资源组中。The number of parameters you provide varies based on whether the resource is a parent or child resource, and whether the resource is in the same subscription or resource group.

若要获取同一订阅和资源组中父资源的资源 ID,请提供资源的类型和名称。To get the resource ID for a parent resource in the same subscription and resource group, provide the type and name of the resource.

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

若要获取子资源的资源 ID,请注意资源类型中段的数目。To get the resource ID for a child resource, pay attention to the number of segments in the resource type. 请提供资源类型的每个段的资源名称。Provide a resource name for each segment of the resource type. 段的名称对应于针对层次结构的该部分存在的资源。The name of the segment corresponds to the resource that exists for that part of the hierarchy.

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

对于属于同一订阅但属于不同资源组的资源,若要获取其资源 ID,请提供资源组名称。To get the resource ID for a resource in the same subscription but different resource group, provide the resource group name.

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

若要获取位于不同订阅和资源组中的资源的资源 ID,请提供订阅 ID 和资源组名称。To get the resource ID for a resource in a different subscription and resource group, provide the subscription ID and resource group name.

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

通常,在替代资源组中使用存储帐户或虚拟网络时,需要使用此函数。Often, you need to use this function when using a storage account or virtual network in an alternate resource group. 以下示例演示了如何轻松使用外部资源组中的资源:The following example shows how a resource from an external resource group can easily be used:

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
      "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": [
  {
      "apiVersion": "2015-05-01-preview",
      "type": "Microsoft.Network/networkInterfaces",
      "name": "[parameters('nicName')]",
      "location": "[parameters('location')]",
      "properties": {
          "ipConfigurations": [{
              "name": "ipconfig1",
              "properties": {
                  "privateIPAllocationMethod": "Dynamic",
                  "subnet": {
                      "id": "[variables('subnet1Ref')]"
                  }
              }
          }]
       }
  }]
}

资源 ID 示例Resource ID example

以下示例模板返回资源组中存储帐户的资源 ID:The following example template returns the resource ID for a storage account in the resource group:

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

上述示例中使用默认值的输出为:The output from the preceding example with the default values is:

名称Name 类型Type Value
sameRGOutputsameRGOutput StringString /subscriptions/{current-sub-id}/resourceGroups/examplegroup/providers/Microsoft.Storage/storageAccounts/examplestorage/subscriptions/{current-sub-id}/resourceGroups/examplegroup/providers/Microsoft.Storage/storageAccounts/examplestorage
differentRGOutputdifferentRGOutput StringString /subscriptions/{current-sub-id}/resourceGroups/otherResourceGroup/providers/Microsoft.Storage/storageAccounts/examplestorage/subscriptions/{current-sub-id}/resourceGroups/otherResourceGroup/providers/Microsoft.Storage/storageAccounts/examplestorage
differentSubOutputdifferentSubOutput StringString /subscriptions/11111111-1111-1111-1111-111111111111/resourceGroups/otherResourceGroup/providers/Microsoft.Storage/storageAccounts/examplestorage/subscriptions/11111111-1111-1111-1111-111111111111/resourceGroups/otherResourceGroup/providers/Microsoft.Storage/storageAccounts/examplestorage
nestedResourceOutputnestedResourceOutput StringString /subscriptions/{current-sub-id}/resourceGroups/examplegroup/providers/Microsoft.SQL/servers/serverName/databases/databaseName/subscriptions/{current-sub-id}/resourceGroups/examplegroup/providers/Microsoft.SQL/servers/serverName/databases/databaseName

订阅subscription

subscription()

返回有关当前部署的订阅的详细信息。Returns details about the subscription for the current deployment.

返回值Return value

该函数返回以下格式:The function returns the following format:

{
    "id": "/subscriptions/{subscription-id}",
    "subscriptionId": "{subscription-id}",
    "tenantId": "{tenant-id}",
    "displayName": "{name-of-subscription}"
}

备注Remarks

使用嵌套模板部署到多个订阅时,可以指定评估 subscription 函数的范围。When using nested templates to deploy to multiple subscriptions, you can specify the scope for evaluating the subscription function. 有关详细信息,将 Azure 资源部署到多个订阅或资源组For more information, see Deploy Azure resources to more than one subscription or resource group.

订阅示例Subscription example

以下示例模板显示了在 outputs 节中调用的 subscription 函数。The following example template shows the subscription function called in the outputs section.

{
    "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "resources": [],
    "outputs": {
        "subscriptionOutput": {
            "value": "[subscription()]",
            "type" : "object"
        }
    }
}

subscriptionResourceIdsubscriptionResourceId

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

返回在订阅级别部署的资源的唯一标识符。Returns the unique identifier for a resource deployed at the subscription level.

参数Parameters

参数Parameter 必需Required 类型Type 说明Description
subscriptionIdsubscriptionId No 字符串(GUID 格式)string (in GUID format) 默认值为当前订阅。Default value is the current subscription. 如果需要检索另一个订阅中的资源,请指定此值。Specify this value when you need to retrieve a resource in another subscription.
resourceTyperesourceType Yes 字符串string 资源类型,包括资源提供程序命名空间。Type of resource including resource provider namespace.
resourceName1resourceName1 Yes 字符串string 资源的名称。Name of resource.
resourceName2resourceName2 No 字符串string 下一个资源名称段(如果需要)。Next resource name segment, if needed.

如果资源类型包含更多段,则继续添加资源名称作为参数。Continue adding resource names as parameters when the resource type includes more segments.

返回值Return value

使用以下格式返回标识符:The identifier is returned in the following format:

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

备注Remarks

我们使用此函数获取部署到订阅而不是资源组的资源的资源 ID。You use this function to get the resource ID for resources that are deployed to the subscription rather than a resource group. 返回的 ID 不同于 resourceId 函数返回的值,区别在于不包含资源组值。The returned ID differs from the value returned by the resourceId function by not including a resource group value.

subscriptionResourceID 示例subscriptionResourceID example

以下模板分配内置角色。The following template assigns a built-in role. 可以将它部署到资源组或订阅。You can deploy it to either a resource group or subscription. 它使用 subscriptionResourceId 函数获取内置角色的资源 ID。It uses the subscriptionResourceId function to get the resource ID for built-in roles.

{
    "$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": "2018-09-01-preview",
            "name": "[parameters('roleNameGuid')]",
            "properties": {
                "roleDefinitionId": "[variables(parameters('builtInRoleType'))]",
                "principalId": "[parameters('principalId')]"
            }
        }
    ]
}

tenantResourceIdtenantResourceId

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

返回在租户级别部署的资源的唯一标识符。Returns the unique identifier for a resource deployed at the tenant level.

参数Parameters

参数Parameter 必需Required 类型Type 说明Description
resourceTyperesourceType Yes 字符串string 资源类型,包括资源提供程序命名空间。Type of resource including resource provider namespace.
resourceName1resourceName1 Yes 字符串string 资源的名称。Name of resource.
resourceName2resourceName2 No 字符串string 下一个资源名称段(如果需要)。Next resource name segment, if needed.

如果资源类型包含更多段,则继续添加资源名称作为参数。Continue adding resource names as parameters when the resource type includes more segments.

返回值Return value

使用以下格式返回标识符:The identifier is returned in the following format:

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

备注Remarks

我们使用此函数获取部署到租户的资源的资源 ID。You use this function to get the resource ID for a resource that is deployed to the tenant. 返回的 ID 不同于其他资源 ID 函数返回的值,区别在于不包含资源组值或订阅值。The returned ID differs from the values returned by other resource ID functions by not including resource group or subscription values.

tenantResourceId 示例tenantResourceId example

内置策略定义是租户级别的资源。Built-in policy definitions are tenant level resources. 若要部署引用内置策略定义的策略分配,请使用 tenantResourceId 函数。To deploy a policy assignment that references a built-in policy definition, use the tenantResourceId function.

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "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."
      }
    },
    "policyDefinitionID": {
      "type": "string",
      "defaultValue": "0a914e76-4921-4c19-b460-a2d36003525a",
      "metadata": {
        "description": "Specifies the ID of the policy definition or policy set definition being assigned."
      }
    }
  },
  "resources": [
    {
      "type": "Microsoft.Authorization/policyAssignments",
      "name": "[parameters('policyAssignmentName')]",
      "apiVersion": "2019-09-01",
      "properties": {
        "scope": "[subscriptionResourceId('Microsoft.Resources/resourceGroups', resourceGroup().name)]",
        "policyDefinitionId": "[tenantResourceId('Microsoft.Authorization/policyDefinitions', parameters('policyDefinitionID'))]"
      }
    }
  ]
}

后续步骤Next steps