Resource functions for Bicep

Resource Manager provides the following functions for getting resource values in your Bicep file:

To get values from the current deployment, see Deployment value functions.

extensionResourceId

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

Returns the resource ID for an extension resource, which is a resource type that is applied to another resource to add to its capabilities.

The extensionResourceId function is available in Bicep files, but typically you don't need it. Instead, use the symbolic name for the resource and access the id property.

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.

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}

A custom policy definition deployed to a management group is implemented as an extension resource. To create and assign a policy, deploy the following Bicep file to a management group.

targetScope = 'managementGroup'

@description('An array of the allowed locations, all other locations will be denied by the created policy.')
param allowedLocations array = [
  'australiaeast'
  'australiasoutheast'
  'australiacentral'
]

resource policyDefinition 'Microsoft.Authorization/policyDefinitions@2019-09-01' = {
  name: 'locationRestriction'
  properties: {
    policyType: 'Custom'
    mode: 'All'
    parameters: {}
    policyRule: {
      if: {
        not: {
          field: 'location'
          in: allowedLocations
        }
      }
      then: {
        effect: 'deny'
      }
    }
  }
}

resource policyAssignment 'Microsoft.Authorization/policyAssignments@2019-09-01' = {
  name: 'locationAssignment'
  properties: {
    policyDefinitionId: policyDefinition.id
  }
}

Built-in policy definitions are tenant level resources. For an example of deploying a built-in policy definition, see tenantResourceId.

getSecret

keyVaultName.getSecret(secretName)

Returns a secret from an Azure Key Vault. The getSecret function can only be called on a Microsoft.KeyVault/vaults resource. Use this function to pass a secret to a secure string parameter of a Bicep module. The function can be used only with a parameter that has the @secure() decorator.

Parameters

Parameter Required Type Description
secretName Yes string The name of the secret stored in a key vault.

Return value

The secret value for the secret name.

Example

The following Bicep file is used as a module. It has an adminPassword parameter defined with the @secure() decorator.

param sqlServerName string
param adminLogin string

@secure()
param adminPassword string

resource sqlServer 'Microsoft.Sql/servers@2020-11-01-preview' = {
  ...
}

The following Bicep file consumes the preceding Bicep file as a module. The Bicep file references an existing key vault, and calls the getSecret function to retrieve the key vault secret, and then passes the value as a parameter to the module.

param sqlServerName string
param adminLogin string

param subscriptionId string
param kvResourceGroup string
param kvName string

resource kv 'Microsoft.KeyVault/vaults@2019-09-01' existing = {
  name: kvName
  scope: resourceGroup(subscriptionId, kvResourceGroup )
}

module sql './sql.bicep' = {
  name: 'deploySQL'
  params: {
    sqlServerName: sqlServerName
    adminLogin: adminLogin
    adminPassword: kv.getSecret('vmAdminPassword')
  }
}

list*

resourceName.list([apiVersion], [functionValues])

You can call a list function for any resource type with an operation that starts with list. Some common usages are list, listKeys, listKeyValue, and listSecrets.

The syntax for this function varies by the name of the list operation. The returned values also vary by operation. Bicep doesn't currently support completions and validation for list* functions.

With Bicep version 0.4.412 or later, you call the list function by using the accessor operator. For example, stg.listKeys().

Parameters

Parameter Required Type Description
apiVersion No string If you don't provide this parameter, the API version for the resource is used. Only provide a custom API version when you need the function to be run with a specific version. Use the format, yyyy-mm-dd.
functionValues No object An object that has values for the function. 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. Don't use a list function that exposes sensitive information in the outputs section of a Bicep file. Output values are stored in the deployment history and could be retrieved by a malicious user.

When used with property loop, you can use the list functions for input because the expression is assigned to the resource property. You can't use them with count because the count must be determined before the list function is resolved.

If you use a list function in a resource that is conditionally deployed, the function is evaluated even if the resource isn't deployed. You get an error if the list function refers to a resource that doesn't exist. Use the conditional expression ?: operator to make sure the function is only evaluated when the resource is being deployed.

Return value

The returned object varies by the list function you use. 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. To see the format of a function, include it in the outputs section as shown in the example Bicep file.

List example

The following example deploys a storage account and then calls listKeys on that storage account. The key is used when setting a value for deployment scripts.

resource stg 'Microsoft.Storage/storageAccounts@2019-06-01' = {
  name: 'dscript${uniqueString(resourceGroup().id)}'
  location: location
  kind: 'StorageV2'
  sku: {
    name: 'Standard_LRS'
  }
}

resource dScript 'Microsoft.Resources/deploymentScripts@2019-10-01-preview' = {
  name: 'scriptWithStorage'
  location: location
  ...
  properties: {
    azCliVersion: '2.0.80'
    storageAccountSettings: {
      storageAccountName: stg.name
      storageAccountKey: stg.listKeys().keys[0].value
    }
    ...
  }
}

The next example shows a list function that takes a parameter. In this case, the function is listAccountSas. Pass an object for the expiry time. The expiry time must be in the future.

param accountSasProperties object {
  default: {
    signedServices: 'b'
    signedPermission: 'r'
    signedExpiry: '2020-08-20T11:00:00Z'
    signedResourceTypes: 's'
  }
}
...
sasToken: stg.listAccountSas('2021-04-01', accountSasProperties).accountSasToken

Implementations

The possible uses of list* are shown in the following table.

Resource type Function name
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.Blockchain/blockchainMembers listApiKeys
Microsoft.Blockchain/blockchainMembers/transactionNodes listApiKeys
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 listConnectionStrings
Microsoft.DocumentDB/databaseAccounts listKeys
Microsoft.DocumentDB/databaseAccounts/notebookWorkspaces listConnectionInfo
Microsoft.DomainRegistration listDomainRecommendations
Microsoft.DomainRegistration/topLevelDomains listAgreements
Microsoft.EventGrid/domains listKeys
Microsoft.EventGrid/topics listKeys
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/users ListEnvironments
Microsoft.LabServices/users ListLabs
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.MachineLearningServices/workspaces/computes listKeys
Microsoft.MachineLearningServices/workspaces/computes listNodes
Microsoft.MachineLearningServices/workspaces listKeys
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 list
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.ServiceBus/namespaces/topics/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 list
Microsoft.Web/sites/config list
microsoft.web/sites/functions listkeys
microsoft.web/sites/functions listsecrets
microsoft.web/sites/hybridconnectionnamespaces/relays listkeys
microsoft.web/sites listsyncfunctiontriggerstatus
microsoft.web/sites/slots/functions listsecrets
microsoft.web/sites/slots/backups list
Microsoft.Web/sites/slots/config list
microsoft.web/sites/slots/functions listsecrets

To determine which resource types have a list operation, you have the following options:

  • View the REST API operations for a resource provider, and look for list operations. For example, storage accounts have the listKeys operation.

  • Use the Get-‚ÄčAzProvider‚ÄčOperation PowerShell cmdlet. The following example gets all list operations for storage accounts:

    Get-AzProviderOperation -OperationSearchString "Microsoft.Storage/*" | where {$_.Operation -like "*list*"} | FT Operation
    
  • 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')]"
    

pickZones

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

Determines whether a resource type supports zones for a region.

Parameters

Parameter Required Type Description
providerNamespace Yes string The resource provider namespace for the resource type to check for zone support.
resourceType Yes string The resource type to check for zone support.
location Yes string The region to check for zone support.
numberOfZones No integer The number of logical zones to return. The default is 1. The number must be a positive integer from 1 to 3. Use 1 for single-zoned resources. For multi-zoned resources, the value must be less than or equal to the number of supported zones.
offset No integer The offset from the starting logical zone. The function returns an error if offset plus numberOfZones exceeds the number of supported zones.

Return value

An array with the supported zones. When using the default values for offset and numberOfZones, a resource type and region that supports zones returns the following array:

[
    "1"
]

When the numberOfZones parameter is set to 3, it returns:

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

When the resource type or region doesn't support zones, an empty array is returned.

[
]

pickZones example

The following Bicep file shows three results for using the pickZones function.

output supported array = pickZones('Microsoft.Compute', 'virtualMachines', 'westus2')
output notSupportedRegion array = pickZones('Microsoft.Compute', 'virtualMachines', 'northcentralus')
output notSupportedType array = pickZones('Microsoft.Cdn', 'profiles', 'westus2')

The output from the preceding examples returns three arrays.

Name Type Value
supported array [ "1" ]
notSupportedRegion array []
notSupportedType array []

You can use the response from pickZones to determine whether to provide null for zones or assign virtual machines to different zones.

reference

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

Returns an object representing a resource's runtime state.

The reference function is available in Bicep files, but typically you don't need it. Instead, use the symbolic name for the resource.

The following example deploys a storage account. It uses the symbolic name stg for the storage account to return a property.

param storageAccountName string

resource stg 'Microsoft.Storage/storageAccounts@2019-06-01' = {
  name: storageAccountName
  location: 'eastus'
  kind: 'Storage'
  sku: {
    name: 'Standard_LRS'
  }
}

output storageEndpoint object = stg.properties.primaryEndpoints

To get a property from an existing resource that isn't deployed in the template, use the existing keyword:

param storageAccountName string

resource stg 'Microsoft.Storage/storageAccounts@2019-06-01' existing = {
  name: storageAccountName
}

// use later in template as often as needed
output blobAddress string = stg.properties.primaryEndpoints.blob

For more information, see Reference resources and the JSON template reference function.

resourceId

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

Returns the unique identifier of a resource.

The resourceId function is available in Bicep files, but typically you don't need it. Instead, use the symbolic name for the resource and access the id property.

You use this function when the resource name is ambiguous or not provisioned within the same Bicep file. 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.

For example:

param storageAccountName string

resource stg 'Microsoft.Storage/storageAccounts@2019-06-01' = {
  name: storageAccountName
  location: 'eastus'
  kind: 'Storage'
  sku: {
    name: 'Standard_LRS'
  }
}

output storageID string = stg.id

To get the resource ID for a resource that isn't deployed in the Bicep file, use the existing keyword.

param storageAccountName string

resource stg 'Microsoft.Storage/storageAccounts@2019-06-01' existing = {
    name: storageAccountName
}

output storageID string = stg.id

For more information, see the JSON template resourceId function

subscriptionResourceId

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

Returns the unique identifier for a resource deployed at the subscription level.

The subscriptionResourceId function is available in Bicep files, but typically you don't need it. Instead, use the symbolic name for the resource and access the id property.

The identifier is returned in the following format:

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

Remarks

You use this function to get the resource ID for resources that are deployed to the subscription rather than a resource group. The returned ID differs from the value returned by the resourceId function by not including a resource group value.

subscriptionResourceID example

The following Bicep file assigns a built-in role. You can deploy it to either a resource group or subscription. It uses the subscriptionResourceId function to get the resource ID for built-in roles.

param principalId string {
  metadata: {
    'description': 'principalId'
  }
}
param builtInRoleType string {
  'allowed': [
    'Owner'
    'Contributor'
    'Reader'
  ]
  'metadata': {
      'description': 'Built-in role to assign'
  }
}

var roleDefinitionId = {
  Owner: {
    id: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', '8e3af657-a8ff-443c-a75c-2fe8c4bcb635')
  }
  Contributor: {
    id: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', 'b24988ac-6180-42a0-ab88-20f7382dd24c')
  }
  Reader: {
    id: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', 'acdd72a7-3385-48ef-bd42-f606fba81ae7')
  }
}

resource myRoleAssignment 'Microsoft.Authorization/roleAssignments@2018-09-01-preview' = {
  name: guid(resourceGroup().id, principalId, roleDefinitionId[builtInRoleType].id)
  properties: {
    roleDefinitionId: roleDefinitionId[builtInRoleType].id
    principalId: principalId
  }
}

tenantResourceId

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

Returns the unique identifier for a resource deployed at the tenant level.

The tenantResourceId function is available in Bicep files, but typically you don't need it. Instead, use the symbolic name for the resource and access the id property.

The identifier is returned in the following format:

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

Built-in policy definitions are tenant level resources. To deploy a policy assignment that references a built-in policy definition, use the tenantResourceId function.

param policyDefinitionID string{
  default: '0a914e76-4921-4c19-b460-a2d36003525a'
  metadata: {
    'description': 'Specifies the ID of the policy definition or policy set definition being assigned.'
  }
}

param policyAssignmentName string {
  default: guid(policyDefinitionID, resourceGroup().name)
  metadata: {
    'description': 'Specifies the name of the policy assignment, can be used defined or an idempotent name as the defaultValue provides.'
  }
}

resource myPolicyAssignment 'Microsoft.Authorization/policyAssignments@2019-09-01' = {
  name: policyAssignmentName
  properties: {
    scope: subscriptionResourceId('Microsoft.Resources/resourceGroups', resourceGroup().name)
    policyDefinitionId: tenantResourceId('Microsoft.Authorization/policyDefinitions', policyDefinitionID)
  }
}

Next steps