How to Randomly Generate a Resource Name With Bicep

In this blog post, we will show how to generate a resource name for a resource with Bicep randomly.

When creating multiple resources on Azure with Bicep, sometimes there is a need to generate a random name for a new resource. A classic example is a storage account.

Bicep Function

Out of the box, Bicep comes packed with many functions that can help us automate things without needing to reinvent the wheel.

In the following Bicep template, I’m using the UniqueString function to generate a hash value based on parameters.

Template

I’m creating a storage account in the code below that will get a new name every time I run the template. I’m also using another built-in function to generate the UTC and use it as a hash to create a unique name.

The storage account name will always start with the word ntweekly.


param location string = resourceGroup().location
param utc string = utcNow()
var storageaccountname  = 'ntweekly${uniqueString(utc)}'

resource storageAccount 'Microsoft.Storage/storageAccounts@2019-06-01' = {
  name: storageaccountname
  location: location
  sku: {
    name: 'Standard_LRS'
  }
  kind: 'StorageV2'
  properties: {
    accessTier: 'Hot'
  }
}

After running the code twice, two storage accounts were created with different names, as shown below.

Published
Categorized as Bicep

1 comment

Leave a comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.