I want to create a function that computes a unique string based on the deployment scope’s ID, e.g. subscription or resource group.
Consider the following:
@export()
@description('Get a unique string based on the resource group ID')
func getResourceNameSuffix(length resourceNameSuffixLength) resourceNameSuffix =>
take(uniqueString(resourceGroup().id), length)
This would only work, if the current file’s deployment scope is a resource group.
I would like to make it generic, so I can also call it from a subscription scope, e.g.:
@export()
@description('Get a unique string based on the resource group ID')
func getResourceNameSuffix(length resourceNameSuffixLength) resourceNameSuffix =>
take(uniqueString(scope().id), length)
But I can’t find such generic scope()
function. Is there a way to get the ID of the current scope dynamically?
Bonus:
Is it possible to throw exceptions in Bicep, so that I could throw an exception from getResourceNameSuffix()
, if it was called from a management group scope?
2
Answers
Within the Bicep file, it is not exactly possible to dynamically retrieve the current deployment scope as it is not explicitly defined but later retrieved based on the deployment context.
Usually, to get to know the current deployment scope of bicep file
targetscope
has to be the main way. Based on thetargetscope
parameter value, the deployment scope can be easily known.And also, there is a function called
scope
available in bicep which is used to specify a different deployment scope other than the default or the root deployment. After the deployment, this scope Id value can be known based on the deployment context.The other workaround is using deployment() function in bicep which,
I have created a sample bicep file to deploy a new resource group as shown below. I have used a
deployment()
function as mentioned and it retrieved all the relevant information of the current deployment.Later, if I click on the
$schema
template link from theoutput
block, it redirects to the detailed template output as shown below. There also, you can be able to view the current deployment scope.Mentioning all of the above, I would suggest you use scope Id externally to set the deployment scope or refer to the bicep file to know the target scope and proceed further to avoid conflicts.
You could always pass the scope to your function:
This would work for subscription and resource group. I don’t think there is much you could do for management group scope.