A better way to reference resources? #16324
-
I do this sequence A LOT in my templates. param privateDnsResourceId string
var splitPrivateDnsResourceId = split(privateDnsResourceId, '/')
var privateDnsSubscriptionId = splitPrivateDnsResourceId[2]
var privateDnsResourceGroupName = splitPrivateDnsResourceId[4]
var privateDnsZoneName = last(splitPrivateDnsResourceId)
resource privateDnsZone 'Microsoft.Network/privateDnsZones@2024-06-01' existing = {
scope: resourceGroup(privateDnsSubscriptionId, privateDnsResourceGroupName)
name: privateDnsZoneName
} Not just for DNS either, it happens for many other resources as well. Is there a better pattern for doing this? I would love to be able to do this: param privateDnsResourceId string
resource privateDnsZone 'whatever' existing = {
resourceId: privateDnsResourceId
}
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
I am not from Microsoft but I can offer this approach here: https://cloudadministrator.net/2024/12/10/azure-resources-cmk-encryption-with-azure-bicep/ where you provide different parameters for the existing resource instead one parameter for the resource ID. For me this is the better approach but I will leave to you to decide on your own. |
Beta Was this translation helpful? Give feedback.
-
I use the same approach as @slavizh. But if you don't want that (or like that) approach you can use User-Defined Functions to avoid repetition (= cleaner Bicep code): func getResourceInformation(resourceId string) resourceInformationType => {
subscriptionId: split(resourceId, '/')[2]
resourceGroupName: split(resourceId, '/')[4]
resourceName: last(split(resourceId, '/'))
}
type resourceInformationType = {
subscriptionId: string
resourceGroupName: string
resourceName: string
} To use it call the functions like this in your Bicep: var varPrivateDnsZone = getResourceInformation('my-resource-id-here')
resource resDnsZone 'Microsoft.Network/privateDnsZones@2024-06-01' existing = {
name: varPrivateDnsZone.resourceName
scope: resourceGroup(varPrivateDnsZone.subscriptionId, varPrivateDnsZone.resourceGroupName)
} It also works with autocompletion (because of the User-Defined Type): The great thing is that you can mark User-Defined Functions with @jachin84 This is the "cleanest" approach to avoid repetition in my opinion 😄 Hope it helps! |
Beta Was this translation helpful? Give feedback.
I use the same approach as @slavizh. But if you don't want that (or like that) approach you can use User-Defined Functions to avoid repetition (= cleaner Bicep code):
To use it call the functions like this in your Bicep: