Search code examples
azure-resource-managerazure-bicep

Don't create any resources if a resource name is taken


We have a bicep file with a dozen related resources and a resource name prefix as a parameter (with the postfixes hardcoded).

Is there a bicep/ARM way to first check if any of the resulting (prefix+postfix) resource names are taken before creating any of the resources?

I tried --what-if and it doesn't detect if a resource name is taken.

I know about the uniqueString function. We could also introduce a parameter for each resource name with a default and run the bicep file again with a different resource name for the offending resource.

A non-bicep way of checking would be to use the REST API / CLI to check a resource name is taken.


Solution

  • Bicep don't have any ways to check resource name availability. Bicep only used to interact with Resource manager controller and pass the resource declaration to create resource.

    If you want to check if the resource exists or not for any particular resource provider the best way is to use REST API which internally used by ARM also.

    REST API: https://learn.microsoft.com/en-us/rest/api/resources/resources/check-existence?view=rest-resources-2021-04-01

    The REST API Varies based on type of resource providers. Example REST API for Api Management validating the resource name availability:

    POST https://management.azure.com/subscriptions/{subscriptionId}/providers/*Microsoft.ApiManagement*/checkNameAvailability?api-version=2022-08-01

    Example REST API for ServiceBus validating the resource name availability: GET https://management.core.windows.net/{subscription ID}/services/ServiceBus/CheckNamespaceAvailability/?namespace=

    How to check whether a resource exists

    HEAD https://management.azure.com/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}?api-version=2021-04-01

    Reference: https://learn.microsoft.com/en-us/rest/api/resources/resources/check-existence?view=rest-resources-2021-04-01