Azure Bicep - Unique Names
Azure Bicep - Unique Names

Azure Bicep – Generate Unique Resource Names

In previous article, we have seen how to use configuration set pattern. In this article, we are going to discuss about a specific problem and its possible solution.

The Problem Statement

When we work with bicep files, we may need to create multiple resources. As the script may be reused multiple times to create same resources, it is a tricky task to decide on a strategy to ensure that unique names are generated for resources. The resource names must be meaningful, unique, deterministic and different for each environment.

The idea is , whenever we redeploy a bicep script with same parameter values, it should create resources with same names. Those names must be unique, from the names generated from other parameter values. Also, each resource’s name has different scope, thus scope of uniqueness depends on the resource.

The Solution

There are two important things that we are going to use to solve this problem:

The string interpolation syntax is similar to what we have in C#, A $ sign followed by opening and losing curly brackets (i.e. ${someVariable}). If the resource needs globally unique name then the uniqueString() function can be used. If we decide to use this function, it is better to use a meaningful prefix, so that we can easily identify the application and the resource.

The uniqueString() function needs a seed value, which can be passed as parameter. In many templates, we can see that resource group identifier is used as seed value. As per documentation, this value should be sufficient to generate unique names for most of the scenarios. Do not use names of resource group (or any other resource) as they may not be sufficiently unique.

Another thing is, if the resource is deployed by using a bicep template, then it is not a good idea to change the seed value later – as it would change the logic of generating unique names.

If you are writing the Bicep modules which can be reused, it may be better idea to take names as parameters, so that the consuming party can decide the pattern of the names.

Demo

The code snippet given below shows an example of the strategy described above. It uses the app name and a short name of the resource as prefix. The prefix is followed by environment name and uniqueString() function in order to make the name unique.

I hope you find this information helpful. Let me know your thoughts.

Leave a Reply Cancel reply