ARM 템플릿의 리소스 함수

Resource Manager는 Azure Resource Manager 템플릿(ARM 템플릿)에서 리소스 값을 가져오기 위한 다음 함수를 제공합니다.

매개 변수, 변수 또는 현재 배포에서 값을 가져오려면 배포 값 함수를 참조하세요.

배포 범위 값을 가져오려면 범위 함수를 참조하세요.

ARM 템플릿과 동일한 기능을 제공하고 구문이 사용하기 더 쉽기 때문에 Bicep를 권장합니다. 자세한 내용은 리소스 함수를 참조하세요.

extensionResourceId

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

확장 리소스에 대한 리소스 ID를 반환합니다. 확장 리소스는 해당 기능에 추가하기 위해 다른 리소스에 적용되는 리소스 종류입니다.

Bicep에서 extensionResourceId 함수를 사용합니다.

매개 변수

매개 변수 필수 Type 설명
baseResourceId string 확장 리소스가 적용되는 리소스의 리소스 ID입니다.
resourceType string 리소스 공급자 네임스페이스를 포함하는 확장 리소스의 유형입니다.
resourceName1 string 확장 리소스의 이름입니다.
resourceName2 아니요 string 필요한 경우 다음 리소스 이름 세그먼트입니다.

리소스 종류에 더 많은 세그먼트가 포함된 경우 리소스 이름을 매개 변수로 계속 추가합니다.

반환 값

이 함수에서 반환되는 리소스 ID의 기본 형식은 다음과 같습니다.

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

범위 세그먼트는 확장되는 기본 리소스에 따라 달라집니다. 예를 들어 구독 ID는 리소스 그룹 ID와 세그먼트가 다릅니다.

확장 리소스가 리소스에 적용되는 경우 리소스 ID는 다음 형식으로 반환됩니다.

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

확장 리소스가 리소스 그룹에 적용되는 경우 반환된 형식은 다음과 같습니다.

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

리소스 그룹과 함께 이 기능을 사용하는 예는 다음 섹션에 나와 있습니다.

확장 리소스가 구독에 적용되는 경우 반환된 형식은 다음과 같습니다.

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

확장 리소스가 관리 그룹에 적용되는 경우 반환된 형식은 다음과 같습니다.

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

관리 그룹과 함께 이 기능을 사용하는 예는 다음 섹션에 나와 있습니다.

extensionResourceId 예제

다음 예제에서는 리소스 그룹 잠금의 리소스 ID를 반환합니다.

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

관리 그룹에 배포된 사용자 지정 정책은 확장 리소스로 구현됩니다. 정책을 만들고 할당하려면 관리 그룹에 다음 템플릿을 배포합니다.

{
  "$schema": "https://schema.management.azure.com/schemas/2019-08-01/managementGroupDeploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "metadata": {
    "_generator": {
      "name": "bicep",
      "version": "0.5.6.12127",
      "templateHash": "1532257987028557958"
    }
  },
  "parameters": {
    "targetMG": {
      "type": "string",
      "metadata": {
        "description": "Target Management Group"
      }
    },
    "allowedLocations": {
      "type": "array",
      "defaultValue": [
        "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, listKeys, listKeyValuelistSecrets입니다.

Bicep에서 list* 함수를 사용합니다.

매개 변수

매개 변수 필수 Type 설명
resourceName 또는 resourceIdentifier string 리소스에 대한 고유 식별자.
apiVersion string 리소스 런타임 상태의 API 버전입니다. 일반적으로 yyyy-mm-dd 형식입니다.
functionValues 아니요 개체 함수에 대한 값이 있는 개체입니다. 스토리지 계정에서 listAccountSas와 같이 매개 변수 값이 있는 개체 수신을 지원하는 함수에 대해서만 이 개체를 제공합니다. 함수 값을 전달하는 예제가 이 문서에 나와 있습니다.

올바른 용도

list 함수는 리소스 정의의 속성에서만 사용할 수 있습니다. 템플릿의 출력 섹션에서 중요한 정보를 노출하는 list 함수를 사용하지 마세요. 출력 값은 배포 기록에 저장되며 악의적인 사용자가 이를 검색할 수 있습니다.

속성 반복와 함께 사용하는 경우 식이 리소스 속성에 할당되기 때문에 input에 list 함수를 사용할 수 있습니다. list 함수를 확인하기 전에 개수를 결정해야 하므로 count와 함께 사용할 수 없습니다.

구현

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 listBuildSourceUploadUrl
Microsoft.ContainerRegistry/registries listCredentials
Microsoft.ContainerRegistry/registries listUsages
Microsoft.ContainerRegistry/registries/agentpools listQueueStatus
Microsoft.ContainerRegistry/registries/buildTasks listSourceRepositoryProperties
Microsoft.ContainerRegistry/registries/buildTasks/steps listBuildArguments
Microsoft.ContainerRegistry/registries/taskruns listDetails
Microsoft.ContainerRegistry/registries/webhooks listEvents
Microsoft.ContainerRegistry/registries/runs listLogSasUrl
Microsoft.ContainerRegistry/registries/tasks listDetails
Microsoft.ContainerService/managedClusters listClusterAdminCredential
Microsoft.ContainerService/managedClusters listClusterMonitoringUserCredential
Microsoft.ContainerService/managedClusters listClusterUserCredential
Microsoft.ContainerService/managedClusters/accessProfiles listCredential
Microsoft.DataBox/jobs listCredentials
Microsoft.DataFactory/datafactories/gateways listauthkeys
Microsoft.DataFactory/factories/integrationruntimes listauthkeys
Microsoft.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 작업이 있는 리소스 유형을 확인할 수 있게 다음 PowerShell 옵션이 제공됩니다.

  • 리소스 공급자에 대한 REST API 작업을 보고 list 작업을 찾습니다. 예를 들어 스토리지 계정에는 listKeys 작업이 있습니다.

  • Get-AzProviderOperation PowerShell cmdlet을 사용합니다. 다음 예제에서는 스토리지 계정에 대한 모든 list 작업을 가져옵니다.

    Get-AzProviderOperation -OperationSearchString "Microsoft.Storage/*" | where {$_.Operation -like "*list*"} | FT Operation
    
  • 다음 Azure CLI 명령을 사용하여 목록 작업만 필터링합니다.

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

반환 값

반환된 개체는 사용하는 list 함수에 따라 다릅니다. 예를 들어 스토리지 계정의 listKeys는 다음 형식을 반환합니다.

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

다른 list 함수는 반환 형식이 다릅니다. 함수의 형식을 보려면 예제 템플릿에 표시된 것처럼 outputs 섹션에 포함합니다.

설명

리소스 이름 또는 resourceId 함수를 사용하여 리소스를 지정합니다. 참조된 리소스를 배포하는 동일한 템플릿에서 list 함수를 사용하는 경우 리소스 이름을 사용합니다.

조건부로 배포된 리소스에서 list 함수를 사용하는 경우 리소스가 배포되지 않은 경우에도 함수가 평가됩니다. list 함수가 존재하지 않는 리소스를 참조하면 오류가 발생합니다. if 함수를 사용하여 리소스가 배포될 때만 함수가 평가되는지 확인합니다. 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])

리소스 종류가 지정된 위치 또는 지역의 영역을 지원하는지 여부를 확인합니다. 이 함수는 영역 리소스만 지원합니다. 영역 중복 서비스는 빈 배열을 반환합니다. 자세한 내용은 가용성 영역을 지원하는 Azure 서비스를 참조하세요.

Bicep에서 pickZones 함수를 사용합니다.

매개 변수

매개 변수 필수 Type 설명
providerNamespace string 영역 지원을 확인할 리소스 종류에 대한 리소스 공급자 네임스페이스입니다.
resourceType string 영역 지원을 확인할 리소스 종류입니다.
location string 영역 지원을 확인할 지역입니다.
numberOfZones 아니요 정수 반환할 논리적 영역의 수입니다. 기본값은 1입니다. 숫자는 1~3 사이의 양수여야 합니다. 단일 영역 리소스에 대해 1을 사용합니다. 다중 영역 리소스의 경우 값은 지원되는 영역 수보다 적거나 같아야 합니다.
offset 아니요 정수 시작 논리적 영역의 오프셋입니다. offset과 numberOfZones의 합이 지원되는 영역의 수를 초과하는 경우 함수에서 오류를 반환합니다.

반환 값

지원되는 영역이 있는 배열입니다. offset 및 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')]"
    }
  }
}

이전 예제의 출력은 3개의 배열을 반환합니다.

이름 타입
지원 배열 [ "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')]"
    }
  }
]

providers

공급자 함수는 ARM 템플릿에서 더 이상 사용되지 않습니다. 더는 사용하지 않는 것이 좋습니다. 리소스 공급자의 API 버전을 가져오기 위해 이 함수를 사용한 경우 템플릿에 특정 API 버전을 제공하는 것이 좋습니다. 버전 간에 속성이 변경된 경우 동적으로 반환된 API 버전을 사용하면 템플릿이 손상될 수 있습니다.

Bicep에서 providers 함수는 더 이상 사용되지 않습니다.

공급자 작업은 REST API를 통해 계속 사용할 수 있습니다. ARM 템플릿 외부에서 리소스 공급자에 대한 정보를 가져오는 데 사용할 수 있습니다.

reference

상징적 이름이 없는 템플릿의 경우:

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

상징적 이름이 있는 템플릿의 경우:

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

리소스의 런타임 상태를 나타내는 개체를 반환합니다. 리소스 컬렉션의 런타임 상태를 나타내는 개체 배열을 반환하려면 참조를 확인하세요.

Bicep은 참조 함수를 제공하지만 대부분의 경우 참조 함수가 필요하지 않습니다. 대신 리소스의 상징적 이름을 사용하는 것이 좋습니다. 참조를 확인하세요.

매개 변수

매개 변수 필수 Type 설명
resourceName/resourceIdentifier 또는 symbolicName/resourceIdentifier string 상징적 이름이 없는 템플릿에서는 리소스의 이름 또는 고유 식별자를 지정합니다. 현재 템플릿의 리소스를 참조할 경우 리소스 이름만 매개 변수로 지정합니다. 이전에 배포된 리소스를 참조하거나 리소스 이름이 모호한 경우 리소스 ID를 제공합니다.
상징적 이름이 있는 템플릿에서는 리소스의 상징적 이름 또는 고유 식별자를 지정합니다. 현재 템플릿의 리소스를 참조할 경우 리소스 상징적 이름만 매개 변수로 지정합니다. 이전에 배포한 리소스를 참조할 경우 리소스 ID를 제공합니다.
apiVersion 아니요 string 지정된 리소스의 API 버전입니다. 리소스가 동일한 템플릿 내에서 프로비저닝되지 않은 경우 이 매개 변수가 필요합니다. 일반적으로 yyyy-mm-dd 형식입니다. 리소스에 대한 유효한 API 버전은 템플릿 참조를 참조하세요.
'Full' 아니요 string 전체 리소스 개체를 반환할지 여부를 지정하는 값입니다. 'Full'을 지정하지 않으면 리소스의 속성 개체만 반환됩니다. 전체 개체에는 리소스 ID 및 위치와 같은 값이 포함됩니다.

반환 값

모든 리소스 형식은 reference 함수에 대해 다른 속성을 반환합니다. 이 함수는 미리 정의된 단일 형식을 반환하지 않습니다. 또한 반환되는 값은 'Full' 인수의 값에 따라 다릅니다. 리소스 형식에 대한 속성을 보려면 예제와 같이 outputs 섹션의 개체를 반환합니다.

설명

참조 함수는 이전에 배포한 리소스 또는 현재 템플릿에 배포된 리소스의 런타임 상태를 검색합니다. 이 문서는 두 시나리오에 대한 예제를 보여 줍니다.

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'을 사용합니다. 예를 들어 키 자격 증명 모음 액세스 정책을 설정하려면 가상 머신에 대한 ID 속성을 가져옵니다.

{
  "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 함수는 템플릿 또는 배포의 출력 섹션 및 리소스 정의의 속성에서만 사용할 수 있습니다. 리소스 정의의 type, name, location 및 기타 최상위 속성과 같은 리소스 속성에는 사용할 수 없습니다. 속성 반복과 함께 사용하면 표현식이 리소스 속성에 할당되기 때문에 input에 대해 reference 함수를 사용할 수 있습니다.

reference 함수를 사용하여 복사 루프에서 count 속성의 값을 설정할 수 없습니다. 루프에서 다른 속성을 설정하는 데는 이 함수를 사용할 수 있습니다. reference 함수가 확인되기 전에 해당 속성을 결정해야 하므로 count 속성에 대한 참조가 차단됩니다.

중첩된 템플릿의 출력 섹션에서 reference 함수 또는 list* 함수를 사용하려면 내부 범위 평가를 사용하도록 expressionEvaluationOptions를 설정하거나 중첩된 템플릿 대신 연결된 템플릿을 사용해야 합니다.

조건부로 배포된 리소스에서 reference 함수를 사용하는 경우 리소스가 배포되지 않은 경우에도 함수가 평가됩니다. reference 함수가 존재하지 않는 리소스를 참조하면 오류가 발생합니다. if 함수를 사용하여 리소스가 배포될 때만 함수가 평가되는지 확인합니다. ifreference를 조건부로 배포된 리소스와 함께 사용하는 샘플 템플릿에 대해서는 if 함수를 참조하세요.

암시적 종속성

reference 함수를 사용하여 참조되는 리소스가 동일한 템플릿 내에서 프로비전되는 경우 한 리소스가 다른 리소스에 종속되도록 암시적으로 선언하고, 해당 이름별로 리소스를 참조합니다(리소스 ID 아님). dependsOn 속성도 사용할 필요가 없습니다. 참조 리소스가 배포를 완료할 때까지 함수는 평가되지 않습니다.

리소스 이름, 상징적 이름 또는 식별자

동일한 비상징적 이름 템플릿에 배포된 리소스를 참조하는 경우 리소스 이름을 제공합니다.

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

동일한 상징적 이름 템플릿에 배포된 리소스를 참조하는 경우 리소스의 상징적 이름을 제공합니다.

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

또는

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

동일한 템플릿에 배포되지 않은 리소스를 참조하는 경우 리소스 ID 및 apiVersion을 제공합니다.

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

참조하는 리소스에 대한 모호성을 피하려면 정규화된 리소스 식별자를 제공할 수 있습니다.

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

리소스에 대한 정규화된 참조를 생성할 때 형식과 이름의 세그먼트를 결합하는 순서는 단순히 두 세그먼트의 연결이 아닙니다. 대신, 네임스페이스 뒤에 구체성이 낮은 순으로 형식/이름 쌍의 시퀀스를 사용합니다.

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

예시:

Microsoft.Compute/virtualMachines/myVM/extensions/myExt는 올바릅니다. Microsoft.Compute/virtualMachines/extensions/myVM/myExt는 올바르지 않습니다.

리소스 ID 만들기를 간소화하려면 concat() 함수 대신이 문서에 설명된 resourceId() 함수를 사용합니다.

관리 ID 가져오기

Azure 리소스에 대한 관리 ID는 일부 리소스에 대해 암시적으로 생성되는 확장 리소스 종류입니다. 관리 ID가 템플릿에 명시적으로 정의되어 있지 않기 때문에 ID가 적용되는 리소스를 참조해야 합니다. Full을 사용하여 암시적으로 생성된 ID를 비롯한 모든 속성을 가져옵니다.

패턴은 다음과 같습니다.

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

예를 들어, 가상 머신에 적용되는 관리 ID에 대한 보안 주체 ID를 가져오려면 다음을 사용합니다.

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

또는, 가상 머신 확장 집합에 적용되는 관리 ID에 대한 테넌트 ID를 가져오려면 다음을 사용합니다.

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

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 템플릿으로 변환합니다. 자세한 내용은 참조 리소스/모듈 컬렉션을 참조하세요.

매개 변수

매개 변수 필수 Type 설명
리소스 컬렉션의 상징적 이름 string 현재 템플릿에 정의된 리소스 컬렉션의 상징적 이름입니다. references 함수는 현재 템플릿 외부의 리소스 참조를 지원하지 않습니다.
'전체', '속성' 아니요 string 전체 리소스 개체의 배열을 반환할지 여부를 지정하는 값입니다. 기본값은 'Properties'입니다. 'Full'을 지정하지 않으면 리소스의 속성 개체만 반환됩니다. 전체 개체에는 리소스 ID 및 위치와 같은 값이 포함됩니다.

반환 값

리소스 컬렉션의 배열입니다. 모든 리소스 형식은 reference 함수에 대해 서로 다른 속성을 반환합니다. 또한 반환되는 값은 'Full' 인수의 값에 따라 다릅니다. 자세한 내용은 reference를 참조하세요.

references의 출력 순서는 항상 복사 인덱스 기반의 오름차순으로 정렬됩니다. 따라서 컬렉션에서 인덱스 0이 있는 첫 번째 리소스가 먼저 표시되고 그 뒤에 인덱스 1이 표시됩니다. 예를 들어 [worker-0, worker-1, worker-2, ...]입니다.

앞의 예제에서 worker-0worker-2가 배포되고 worker-1은 false 조건으로 인해 배포되지 않은 경우, 배포되지 않은 리소스는 생략되고 배포된 리소스가 해당 번호순으로 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 함수를 사용합니다.

매개 변수

매개 변수 필수 Type 설명
subscriptionId 아니요 문자열(GUID 형식) 기본값은 현재 구독입니다. 다른 구독에서 리소스를 검색해야 하는 경우 이 값을 지정합니다. 리소스 그룹 또는 구독의 범위에서 배포하는 경우에만 이 값을 제공합니다.
resourceGroupName 아니요 string 기본값은 현재 리소스 그룹입니다. 다른 리소스 그룹에서 리소스를 검색해야 하는 경우 이 값을 지정합니다. 리소스 그룹의 범위에 배포하는 경우에만 이 값을 제공합니다.
resourceType string 리소스 공급자 네임스페이스를 포함하는 리소스 유형입니다.
resourceName1 string 리소스의 이름입니다.
resourceName2 아니요 string 필요한 경우 다음 리소스 이름 세그먼트입니다.

리소스 종류에 더 많은 세그먼트가 포함된 경우 리소스 이름을 매개 변수로 계속 추가합니다.

반환 값

리소스 ID는 다양한 범위에서 다양한 형식으로 반환됩니다.

  • 리소스 그룹 범위:

    /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}
    
  • 구독 범위:

    /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}
    
  • 관리 그룹 또는 테넌트 범위:

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

혼동을 피하기 위해 구독, 관리 그룹 또는 테넌트에 배포된 리소스를 사용할 때 resourceId를 사용하지 않는 것이 좋습니다. 대신 범위에 대해 설계된 ID 함수를 사용합니다.

설명

제공하는 매개 변수 수는 리소스가 부모 리소스인지 또는 자식 리소스인지, 리소스가 동일한 구독에 있는지 또는 리소스 그룹에 있는지에 따라 달라집니다.

동일한 구독 및 리소스 그룹에 있는 부모 리소스의 리소스 ID를 가져오려면 리소스의 종류 및 이름을 제공합니다.

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

자식 리소스의 리소스 ID를 가져오려면 리소스 종류의 세그먼트 수에 주의합니다. 리소스 종류의 각 세그먼트에 대한 리소스 이름을 제공합니다. 세그먼트의 이름은 계층의 해당 부분에 존재하는 리소스에 해당합니다.

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

같은 구독, 다른 리소스 그룹에 있는 리소스의 리소스 ID를 가져오려면 리소스 그룹 이름을 제공합니다.

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

다른 구독 및 리소스 그룹에 있는 리소스의 리소스 ID를 가져오려면 구독 ID와 리소스 그룹 이름을 제공합니다.

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

대체 리소스 그룹의 스토리지 계정 또는 가상 네트워크를 사용할 경우 이 함수를 사용해야 합니다. 다음 예에서는 외부 리소스 그룹의 리소스를 쉽게 사용할 수 있는 방법을 보여 줍니다.

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

리소스 ID 예제

다음 예제에서는 리소스 그룹의 스토리지 계정에 대한 리소스 ID를 반환합니다.

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

기본 값을 사용한 이전 예제의 출력은 다음과 같습니다.

이름 타입
sameRGOutput 문자열 /subscriptions/{current-sub-id}/resourceGroups/examplegroup/providers/Microsoft.Storage/storageAccounts/examplestorage
differentRGOutput 문자열 /subscriptions/{current-sub-id}/resourceGroups/otherResourceGroup/providers/Microsoft.Storage/storageAccounts/examplestorage
differentSubOutput 문자열 /subscriptions/11111111-1111-1111-1111-111111111111/resourceGroups/otherResourceGroup/providers/Microsoft.Storage/storageAccounts/examplestorage
nestedResourceOutput 문자열 /subscriptions/{current-sub-id}/resourceGroups/examplegroup/providers/Microsoft.SQL/servers/serverName/databases/databaseName

구독

구독 범위 기능을 참조하세요.

Bicep에서 subscription 범위 함수를 사용합니다.

subscriptionResourceId

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

구독 수준에서 배포된 리소스의 고유 식별자를 반환합니다.

Bicep에서 subscriptionResourceId 함수를 사용합니다.

매개 변수

매개 변수 필수 Type 설명
subscriptionId 아니요 문자열(GUID 형식) 기본값은 현재 구독입니다. 다른 구독에서 리소스를 검색해야 하는 경우 이 값을 지정합니다.
resourceType string 리소스 공급자 네임스페이스를 포함하는 리소스 유형입니다.
resourceName1 string 리소스의 이름입니다.
resourceName2 아니요 string 필요한 경우 다음 리소스 이름 세그먼트입니다.

리소스 종류에 더 많은 세그먼트가 포함된 경우 리소스 이름을 매개 변수로 계속 추가합니다.

반환 값

식별자는 다음 형식으로 반환됩니다.

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

설명

이 함수를 사용하여 리소스 그룹이 아닌 구독에 배포된 리소스의 리소스 ID를 가져올 수 있습니다. 반환되는 ID는 리소스 그룹 값을 포함하지 않으므로 resourceId 함수에서 반환하는 값과 다릅니다.

subscriptionResourceID 예제

다음 템플릿은 기본 제공 역할을 할당합니다. 리소스 그룹 또는 구독에 배포할 수 있습니다. subscriptionResourceId 함수를 사용하여 기본 제공 역할의 리소스 ID를 가져옵니다.

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

managementGroupResourceId

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

관리 그룹 수준에서 배포된 리소스의 고유 식별자를 반환합니다.

Bicep에서 managementGroupResourceId 함수를 사용합니다.

매개 변수

매개 변수 필수 Type 설명
managementGroupResourceId 아니요 문자열(GUID 형식) 기본값은 현재 관리 그룹입니다. 다른 관리 그룹에서 리소스를 검색해야 하는 경우 이 값을 지정합니다.
resourceType string 리소스 공급자 네임스페이스를 포함하는 리소스 유형입니다.
resourceName1 string 리소스의 이름입니다.
resourceName2 아니요 string 필요한 경우 다음 리소스 이름 세그먼트입니다.

리소스 종류에 더 많은 세그먼트가 포함된 경우 리소스 이름을 매개 변수로 계속 추가합니다.

반환 값

식별자는 다음 형식으로 반환됩니다.

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

설명

이 함수를 사용하여 리소스 그룹이 아닌 관리 그룹에 배포되는 리소스의 리소스 ID를 가져옵니다. 반환된 ID는 구독 ID 및 리소스 그룹 값을 포함하지 않는다는 점에서 resourceId 함수에서 반환된 값과 다릅니다.

managementGroupResourceID 예

다음 템플릿은 정책 정의를 만들고 할당합니다. managementGroupResourceId 함수를 사용하여 정책 정의를 위한 리소스 ID를 가져옵니다.

{
  "$schema": "https://schema.management.azure.com/schemas/2019-08-01/managementGroupDeploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "targetMG": {
      "type": "string",
      "metadata": {
        "description": "Target Management Group"
      }
    },
    "allowedLocations": {
      "type": "array",
      "defaultValue": [
        "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 함수를 사용합니다.

매개 변수

매개 변수 필수 Type 설명
resourceType string 리소스 공급자 네임스페이스를 포함하는 리소스 유형입니다.
resourceName1 string 리소스의 이름입니다.
resourceName2 아니요 string 필요한 경우 다음 리소스 이름 세그먼트입니다.

리소스 종류에 더 많은 세그먼트가 포함된 경우 리소스 이름을 매개 변수로 계속 추가합니다.

반환 값

식별자는 다음 형식으로 반환됩니다.

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

설명

이 함수를 사용하여 테넌트에 배포된 리소스의 리소스 ID를 가져옵니다. 반환되는 ID는 리소스 그룹 또는 구독 값을 포함하지 않으므로 다른 리소스 ID 함수에서 반환하는 값과 다릅니다.

tenantResourceId 예제

기본 제공 정책 정의는 테넌트 수준 리소스입니다. 기본 제공 정책 정의를 참조하는 정책 할당을 배포하려면 tenantResourceId 함수를 사용합니다.

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

다음 단계