bicep using user defined function

User defined function can be quite handy to help us some save time. Here is an example of how we can defned user defined function (like in golang)

func buildResourceName(prefix string, env string, suffix string) string =>
  toLower('${prefix}-${env}-${suffix}')

And to use it we simple call it here in our storage container examples:- 


resource container 'Microsoft.Storage/storageAccounts/blobServices/containers@2023-01-01' = [for name in containers: {
  parent: blobService
  name: buildResourceName(name, 'dev', 'aue')
  properties: {
    publicAccess: 'None'
    metadata: {
      project: 'audit-2026'
    }
  }
}]

You can get all the bicep function here

https://learn.microsoft.com/en-us/azure/azure-resource-manager/bicep/bicep-functions

Placing your function in another file 

You can place all your function in a separate file and import it in. 

functions.bicep

@export() // The @export decorator allows other files to see this
func buildResourceNameProd(prefix string, env string, suffix string) string =>
  toLower('${prefix}-${env}-${suffix}-prod')

And then use it here like so by using the import keyword as myFuncs. Then call it with myFuncs.buildResourceNameProd


import * as myFuncs from 'functions.bicep'

resource container 'Microsoft.Storage/storageAccounts/blobServices/containers@2023-01-01' = [for name in containers: {
  parent: blobService
  name: myFuncs.buildResourceNameProd(name, 'dev', 'aue')
  properties: {
    publicAccess: 'None'
    metadata: {
      project: 'audit-2026'
    }
  }
}]


Comments

Popular posts from this blog

vllm : Failed to infer device type

android studio kotlin source is null error

NodeJS: Error: spawn EINVAL in window for node version 20.20 and 18.20