ARM 範本的資源函式

Resource Manager 提供下列函式,以在您的 Azure Resource Manager (ARM) 範本中取得資源值:

若要從參數、變數或目前的部署中取得值,請參閱 部署值函式

若要取得部署範圍值,請參閱範圍函數

提示

我們建議使用 Bicep,因為其提供的功能與 ARM 範本相同,而且語法更易於使用。 若要深入了解,請參閱資源函式。

extensionResourceId

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

傳回延伸模組資源的資源識別碼。 延伸模組資源是一種資源類型,套用至另一個資源後可新增其功能。

在 Bicep 中,使用 extensionResourceId 函式。

參數

參數 必要 類型​ 描述
baseResourceId Yes string 套用延伸模組資源之資源的資源識別碼。
resourceType Yes string 延伸模組資源的類型 (包括資源提供者命名空間)。
resourceName1 Yes string 延伸模組資源的副檔名。
resourceName2 No string 下一個資源名稱區段 (如有必要)。

當資源類型包含更多區段時,請繼續新增資源名稱作為參數。

傳回值

此函式所傳回之資源識別碼的基本格式為:

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

範圍區段會隨著要擴充的基底資源而不同。 例如,相較於資源群組的識別碼,訂閱的識別碼有不同的區段。

當延伸模組資源套用至資源時,資源識別碼會以下列格式傳回:

/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 範例

下列範例會傳回資源群組鎖定的資源識別碼。

{
  "$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": [
        "australiaeast",
        "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'))]",
    "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 作業的資源類型傳回值。 作業名稱的開頭必須為 list,且可以有尾碼。 常見的使用方式包括 listlistKeyslistKeyValuelistSecrets

在 Bicep 中,使用 list* 函式。

參數

參數 必要 類型​ 描述
resourceName 或 resourceIdentifier Yes string 資源的唯一識別碼。
apiVersion Yes string 資源執行階段狀態的 API 版本。 一般而言,格式為 yyyy-mm-dd
functionValues No object 具有函式值的物件。 僅針對支援接收具有參數值之物件 (例如儲存體帳戶上的 listAccountSas) 的函式提供此物件。 本文會顯示傳遞函式值的範例。

有效用法

清單函式可以在資源定義的屬性中使用。 請勿在範本的輸出區段中使用會公開敏感性資訊的清單函式。 輸出值會儲存在部署歷程記錄中,而且可能會遭到惡意使用者擷取。

屬性反覆運算搭配使用時,您可以將 list 函式用於 input,因為運算式會指派給資源屬性。 您無法將這些函式用於 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.BatchAI/workspaces/experiments/jobs listoutputfiles
Microsoft.BotService/botServices/channels listChannelWithKeys
Microsoft.Cache/redis listKeys
Microsoft.CognitiveServices/accounts listKeys
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.DataLakeAnalytics/accounts/storageAccounts/Containers listSasTokens
Microsoft.DataShare/accounts/shares listSynchronizations
Microsoft.DataShare/accounts/shareSubscriptions listSourceShareSynchronizationSettings
Microsoft.DataShare/accounts/shareSubscriptions listSynchronizationDetails
Microsoft.DataShare/accounts/shareSubscriptions listSynchronizations
Microsoft.Devices/iotHubs listKeys
Microsoft.Devices/iotHubs/iotHubKeys listKeys
Microsoft.Devices/provisioningServices/keys listKeys
Microsoft.Devices/provisioningServices listKeys
Microsoft.DevTestLab/labs ListVhds
Microsoft.DevTestLab/labs/schedules ListApplicable
Microsoft.DevTestLab/labs/users/serviceFabrics ListApplicableSchedules
Microsoft.DevTestLab/labs/virtualMachines 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.LabServices/labs/users 清單
Microsoft.LabServices/labs/virtualMachines 清單
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.MachineLearning/webServices listkeys
Microsoft.MachineLearning/Workspaces listworkspacekeys
Microsoft.Maps/accounts listKeys
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 清單
Microsoft.OperationalInsights/workspaces listKeys
Microsoft.PolicyInsights/remediations listDeployments
Microsoft.RedHatOpenShift/openShiftClusters listCredentials
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.StorSimple/managers/devices listFailoverSets
Microsoft.StorSimple/managers/devices listFailoverTargets
Microsoft.StorSimple/managers listActivationKey
Microsoft.StorSimple/managers listPublicEncryptionKey
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 清單
Microsoft.Web/sites/config 清單
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 清單
Microsoft.Web/sites/slots/config 清單
microsoft.web/sites/slots/functions listSecrets

為判斷哪一個資源類型具有 list 作業,您可以使用下列選項:

  • 檢視資源提供者的 REST API 作業,並尋找 list 作業。 例如,儲存體帳戶具有 listKeys 作業

  • 使用 Get-AzProvider​Operation PowerShell Cmdlet。 下列範例會取得儲存體帳戶的所有 list 作業︰

    Get-AzProviderOperation -OperationSearchString "Microsoft.Storage/*" | where {$_.Operation -like "*list*"} | FT Operation
    
  • 使用下列 Azure CLI 命令可只篩選出 list 作業:

    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 函數具有不同的傳回格式。 若要查看函式的格式,請將函式放入 [輸出] 區段,如範本範例所示。

備註

使用資源名稱或 resourceId 函式來指定資源。 在部署參考資源的相同範本中使用 list 函式時,請使用資源名稱。

如果您在條件式部署的資源中使用 list 函式,即使未部署資源,該函式也會受到評估。 如果 list 函數參考不存在的資源,就會發生錯誤。 請使用 if 函數,以確保只有在部署資源時才會評估函數。 如需對條件式部署的資源搭配使用 iflist 的範例範本,請參閱 if 函式

清單範例

下列範例會在設定部署指令碼的值時使用 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])

判斷資源類型是否支援指定位置或區域 (Region) 的區域 (Zone)。 此函數僅支援區域性資源。 區域備援服務會傳回空白陣列。 如需詳細資訊,請參閱支援可用性區域的 Azure 服務

在 Bicep 中,使用 pickZones 函式。

參數

參數 必要 類型​ 描述
providerNamespace Yes string 用於檢查區域支援的資源類型的資源提供者命名空間。
resourceType Yes string 用於檢查區域支援的資源類型。
location Yes string 用於檢查區域支援的 Azure 區域。
numberOfZones No 整數 要傳回的邏輯區域數目。 預設值是 1。 此數字必須是介於 1 到 3 之間的正整數。 單一區域資源使用 1。 若為多區域資源,此值必須小於或等於支援的區域數目。
offset No 整數 從起始邏輯區域算起的位移。 如果位移加上 numberOfZones 超過支援的區域數目,函式會傳回錯誤。

傳回值

具有支援區域的陣列。 對位移和 numberOfZones 使用預設值時,支援區域的資源類型和區域會傳回下列陣列:

[
    "1"
]

numberOfZones 參數設為 3 時,會傳回:

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

當資源類型或區域不支援區域,會傳回空陣列。 區域備援服務也會傳回空白陣列。

[
]

備註

Azure 可用性區域有不同的類別–區域性和區域備援。 pickZones 函式可以用來傳回區域性資源的可用性區域。 針對區域備援服務 (ZRS),此函式會傳回空白陣列。 區域性資源通常在資源定義的最上層具有 zones 屬性。 若要判斷可用性區域的支援類別,請參閱支援可用性區域的 Azure 服務

若要判斷指定的 Azure 區域或位置是否支援可用性區域,請使用區域性資源類型 (例如 Microsoft.Network/publicIPAddresses) 來呼叫 pickZones 函式。 如果回應非空白,則區域會支援可用性區域。

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', 'westus2')]"
    },
    "notSupportedRegion": {
      "type": "array",
      "value": "[pickZones('Microsoft.Compute', 'virtualMachines', 'westus')]"
    },
    "notSupportedType": {
      "type": "array",
      "value": "[pickZones('Microsoft.Cdn', 'profiles', 'westus2')]"
    }
  }
}

前述範例的輸出會傳回三個陣列。

名稱 類型
服務 陣列 [ "1" ]
notSupportedRegion 陣列 []
notSupportedType 陣列 []

您可以使用 pickZones 的回應來判斷是否向區域提供 Null,或將虛擬機器指派給不同的區域。 下列範例會根據區域的可用性來設定區域的值。

"zones": {
  "value": "[if(not(empty(pickZones('Microsoft.Compute', 'virtualMachines', 'westus2'))), 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')]"
    }
  }
]

提供者

提供者函數已在 ARM 範本中被取代。 我們不再建議使用。 如果您使用此函式來取得資源提供者的 API 版本,建議您在範本中提供特定的 API 版本。 如果使用動態傳回的 API 版本,若版本間發生屬性變更時可能會造成您的範本中斷。

在 Bicep 中,providers 函式已被取代。

providers 作業仍可透過 REST API 取得。 其可以在 ARM 範本外使用,以取得資源提供者的相關資訊。

參考

在沒有符號名稱的範本中:

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

在具有符號名稱的範本中:

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

傳回代表資源執行階段狀態的物件。 函式 reference 的輸出和行為高度依賴每個資源提供者 (RP) 如何實作其 PUT 和 GET 回應。 若要傳回代表資源集合執行階段狀態的物件陣列,請參閱參考

Bicep 會提供參考函式,但在大多數情況下,不需要參考函式。 建議改為使用資源的符號名稱。 請參閱參考

參數

參數 必要 類型​ 描述
resourceName/resourceIdentifier 或 symbolicName/resourceIdentifier Yes string 在沒有符號名稱的範本中,請指定資源的名稱或唯一識別碼。 當參考目前範本中的資源時,只會提供資源名稱做為參數。 參考先前部署的資源時,或資源的名稱不明確時,請提供資源識別碼。
在具有符號名稱的範本中,請指定資源的符號名稱或唯一識別碼。 當參考目前範本中的資源時,僅提供資源符號名稱做為參數。 當參考先前已部署的資源時,會提供資源識別碼。
apiVersion No string 指定的資源的 API 版本。 如果在相同的範本內未佈建資源,則需要此參數。 一般而言,格式為 yyyy-mm-dd。 如需資源的有效 API 版本,請參閱範本參考
'Full' No string 值,指定是否要傳回完整資源物件。 如果您未指定 'Full',則只會傳回資源的屬性物件。 完整物件包括例如資源識別碼和位置的值。

傳回值

每種資源類型都會針對 reference 函式傳回不同屬性。 此函式不會傳回單一的預先定義格式。 此外,傳回的值會根據 'Full' 引數的值而有所不同。 若要查看資源類型的屬性,請在輸出區段中傳回物件,如範例所示。

備註

參照函數會擷取過去部署資源或是目前範本部署資源的狀態。 本文會介紹這兩個案例的範例。

一般而言,您可以使用 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 函數只能用在範本或部署的輸出區段,以及資源定義的屬性物件中。 該函數不能用於資源屬性,例如 typenamelocation 以及其他資源定義的最上層屬性。 與屬性反覆運算搭配使用時,您可以將 reference 函數用於 input,因為運算式會指派給資源屬性。

您無法使用 reference 函數在複製迴圈中設定 count 屬性的值。 您可以使用該函式來設定迴圈中的其他屬性。 計數屬性的參考遭到封鎖,因為在解析 reference 函數之前就必須決定該屬性。

若要在巢狀範本的輸出區段中使用 reference 函式或任何 list* 函式,您必須將 expressionEvaluationOptions 設為使用內部範圍評估,或使用連結範本而非巢狀範本。

如果您在條件式部署的資源中使用 reference 函式,即使未部署資源,該函式也會受到評估。 如果 reference 函數參考不存在的資源,就會發生錯誤。 請使用 if 函數,以確保只有在部署資源時才會評估函數。 如需對條件式部署的資源搭配使用 ifreference 的範例範本,請參閱 if 函式

隱含相依性

如果在相同的範本內佈建參考資源且您會依其名稱 (而非資源識別碼) 來參考該資源,則可使用 reference 函式,隱含地宣告某一個資源相依於另一個資源。 您不需要同時使用 dependsOn 屬性。 所參考的資源完成部署之前不會評估函式。

資源名稱、符號名稱或識別碼

參考部署在相同 none-symbolic-name 範本中的資源時,請提供資源的名稱。

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

參考部署在相同 symbolic-name 範本中的資源時,請提供資源的符號名稱。

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

Or

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

參考未部署在相同範本中的資源時,請提供資源識別碼和 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 為不正確

若要簡化建立任何資源識別碼的程序,請使用本文件中說明的 resourceId() 函式,而不是 concat() 函式。

取得受控識別

適用於 Azure 資源的受控識別是針對某些資源隱含建立的延伸模組資源類型。 由於受控識別未明確定義於範本中,因此您必須參考套用身分識別的資源。 請使用 Full 取得所有屬性,包括隱含建立的身分識別。

模式為:

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

例如,若要針對套用至虛擬機器的受控識別取得主體識別碼,請使用:

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

或者,若要針對套用至虛擬機器擴展集的受控識別取得其租用戶識別碼,請使用:

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

參考範例

下列範例會部署資源,並參考該資源。

{
  "$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.windows.net/",
     "file": "https://examplestorage.file.core.windows.net/",
     "queue": "https://examplestorage.queue.core.windows.net/",
     "table": "https://examplestorage.table.core.windows.net/"
   },
   "primaryLocation": "southcentralus",
   "provisioningState": "Succeeded",
   "statusOfPrimary": "available",
   "supportsHttpsTrafficOnly": false
}

完整物件會使用下列格式:

{
  "apiVersion":"2022-09-01",
  "location":"southcentralus",
  "sku": {
    "name":"Standard_LRS",
    "tier":"Standard"
  },
  "tags":{},
  "kind":"Storage",
  "properties": {
    "creationTime":"2021-10-09T18:55:40.5863736Z",
    "primaryEndpoints": {
      "blob":"https://examplestorage.blob.core.windows.net/",
      "file":"https://examplestorage.file.core.windows.net/",
      "queue":"https://examplestorage.queue.core.windows.net/",
      "table":"https://examplestorage.table.core.windows.net/"
    },
    "primaryLocation":"southcentralus",
    "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 範本。 如需詳細資訊,請參閱參考資源/模組集合

參數

參數 必要 類型​ 描述
資源集合的符號名稱 Yes string 目前範本中定義之資源集合的符號名稱。 references 函式不支援參考目前範本外部的資源。
「Full」、「Properties」 No string 指定是否要傳回完整資源物件陣列的值。 預設值是 'Properties'。 如果您未指定 'Full',則只會傳回資源的屬性物件。 完整物件包括例如資源識別碼和位置的值。

傳回值

資源集合的陣列。 每種資源類型都會針對 reference 函式傳回不同屬性。 此外,傳回的值會根據 'Full' 引數的值而有所不同。 如需詳細資訊,請參閱參考

references 的輸出順序一律會根據複製索引以遞增順序排列。 因此,會先顯示集合中索引為 0 的資源,接著顯示索引為 1 的資源,以此類推。 例如,[worker-0, worker-1, worker-2, ...]

在上述範例中,如果 worker-0worker-2 已部署,而 worker-1 由於錯誤狀況而未部署,則 references 的輸出會省略未部署的資源,並按照已部署資源的編號排序來顯示已部署資源。 references 的輸出為 [worker-0, worker-2, ...]。如果省略所有資源,函式會傳回空陣列。

有效用法

references 函式不能用於資源複製迴圈Bicep for 迴圈。 例如,下列案例中不允許 references

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

若要在巢狀範本的輸出區段中使用 references 函式或任何 list* 函式,您必須將 expressionEvaluationOptions 設為使用內部範圍評估,或使用連結範本而非巢狀範本。

隱含相依性

藉由使用 references 函式,您隱含地宣告某個資源相依於另一個資源。 您不需要同時使用 dependsOn 屬性。 所參考的資源完成部署之前不會評估函式。

參考範例

下列範例會部署資源集合,並參考該資源集合。

{
  "$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 函式。

參數

參數 必要 類型​ 描述
subscriptionId No 字串 (GUID 格式) 預設值為目前的訂用帳戶。 需要擷取另一個訂用帳戶中的資源群組時,請指定此值。 只有在資源群組或訂用帳戶範圍進行部署時,才需要提供此值。
resourceGroupName No string 預設值為目前資源群組。 需要擷取另一個訂用帳戶中的資源群組時,請指定此值。 只有在部署於資源群組範圍時,才需要提供此值。
resourceType Yes string 資源的類型 (包括資源提供者命名空間)。
resourceName1 Yes string 資源的名稱。
resourceName2 No string 下一個資源名稱區段 (如有必要)。

當資源類型包含更多區段時,請繼續新增資源名稱作為參數。

傳回值

資源識別碼會在不同範圍以不同格式傳回:

  • 資源群組範圍:

    /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}
    
  • 訂用帳戶範圍:

    /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}
    
  • 管理群組或租用戶範圍:

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

為了避免混淆,建議您不要在部署至訂閱、管理群組或租用戶的資源時使用 resourceId, 而是使用針對此範圍設計的 ID 函式。

備註

您應提供的參數數目會根據資源是父資源還是子資源,以及資源是否位於相同的訂用帳戶或資源群組中,而有所不同。

若要對相同訂用帳戶和資源群組中的父資源取得資源識別碼,請提供資源的類型和名稱。

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

若要取得子資源的資源識別碼,請注意資源類型中的區段數目。 請提供資源類型中每個區段的資源名稱。 區段的名稱會對應至存在於該階層部分的資源。

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

若要對位於相同訂用帳戶、但不同資源群組中的資源取得資源識別碼,請提供資源群組名稱。

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

若要對不同訂用帳戶和資源群組中的資源取得資源識別碼,請提供訂用帳戶識別碼和資源群組名稱。

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

資源識別碼範例

下列範例會傳回資源群組中儲存體帳戶的資源識別碼:

{
  "$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 String /subscriptions/{current-sub-id}/resourceGroups/examplegroup/providers/Microsoft.Storage/storageAccounts/examplestorage
differentRGOutput String /subscriptions/{current-sub-id}/resourceGroups/otherResourceGroup/providers/Microsoft.Storage/storageAccounts/examplestorage
differentSubOutput String /subscriptions/11111111-1111-1111-1111-111111111111/resourceGroups/otherResourceGroup/providers/Microsoft.Storage/storageAccounts/examplestorage
nestedResourceOutput String /subscriptions/{current-sub-id}/resourceGroups/examplegroup/providers/Microsoft.SQL/servers/serverName/databases/databaseName

訂用帳戶

請參閱訂閱範圍函數

在 Bicep 中,使用 subscription 範圍函式。

subscriptionResourceId

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

傳回部署於訂用帳戶層級之資源的唯一識別碼。

在 Bicep 中,使用 subscriptionResourceId 函式。

參數

參數 必要 類型​ 描述
subscriptionId No 字串 (GUID 格式) 預設值為目前的訂用帳戶。 需要擷取另一個訂用帳戶中的資源群組時,請指定此值。
resourceType Yes string 資源的類型 (包括資源提供者命名空間)。
resourceName1 Yes string 資源的名稱。
resourceName2 No string 下一個資源名稱區段 (如有必要)。

當資源類型包含更多區段時,請繼續新增資源名稱作為參數。

傳回值

識別碼會以下列格式傳回:

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

備註

您可以使用此函式,對部署至訂用帳戶 (而不是資源群組) 的資源取得資源識別碼。 傳回的識別碼與 resourceId 函式所傳回的值不同;其中不含資源群組值。

subscriptionResourceID 範例

下列範本會指派內建角色。 您可以將其部署至資源群組或訂用帳戶。 其會使用 subscriptionResourceId 函數來取得內建角色的資源識別碼。

{
  "$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 函數。

參數

參數 必要 類型​ 描述
managementGroupResourceId No 字串 (GUID 格式) 預設值是目前的管理群組。 需要擷取另一個管理群組中的資源時,請指定此值。
resourceType Yes string 資源的類型 (包括資源提供者命名空間)。
resourceName1 Yes string 資源的名稱。
resourceName2 No string 下一個資源名稱區段 (如有必要)。

當資源類型包含更多區段時,請繼續新增資源名稱作為參數。

傳回值

識別碼會以下列格式傳回:

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

備註

您可以使用此函數,為部署至管理群組 (而不是資源群組) 的資源取得資源識別碼。 傳回的識別碼與 resourceId 函數所傳回的值不同;其中不含訂閱 ID 和資源群組值。

managementGroupResourceID 範例

下列範本會建立並指派原則定義。 其會使用 managementGroupResourceId 函數來取得原則定義的資源識別碼。

{
  "$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": [
        "australiaeast",
        "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'))]",
    "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 函式。

參數

參數 必要 類型​ 描述
resourceType Yes string 資源的類型 (包括資源提供者命名空間)。
resourceName1 Yes string 資源的名稱。
resourceName2 No string 下一個資源名稱區段 (如有必要)。

當資源類型包含更多區段時,請繼續新增資源名稱作為參數。

傳回值

識別碼會以下列格式傳回:

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

備註

您可以使用此函式,對部署至租用戶的資源取得資源識別碼。 傳回的識別碼與其他資源識別碼函式所傳回的值不同;其中不含資源群組或訂用帳戶值。

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

下一步