DEV Community

Cover image for User-defined function in Azure Bicep
Olivier Miossec
Olivier Miossec

Posted on • Edited on

User-defined function in Azure Bicep

Bicep allows you to define your functions for your bicep deployment. These functions can ease standardization expressions frequently used or perform some calculations. Think about naming conventions where you need to concatenate several strings to form a name.
Bicep user-defined functions are similar to user-defined functions in ARM templates but far more simpler.
To declare a function, you simply need to use the “func” statement followed by a list of parameters (if any) with their type, the data type returned by the function, and an expression, the corpus of the function.
Func (param1, param1Type, param2, param2Type, …) functionType => Function Expression
Just like in the ARM template function, the expression can only use the function parameters, it can't access any variable or parameter present in the bicep project.
A simple example to understand.

func sayMyName(firstName string, lastName string) string => '${firstName} ${lastName}'

output myName string = sayMyName('Olivier', 'Miossec')
Enter fullscreen mode Exit fullscreen mode

The function sayMyName takes two parameters, firstName and lastName both using the string type. The function returns a string, which is the concatenation of the two parameters separated by a space.
As you see user user-defined function is Bicep can help to enforce naming conventions. Imagine you want to ensure that a resource name is defined by the name of the application, an increment, and the resource type.

func resourceName (appName string, increment int, resourceType string) string => toLower('${appName}-${increment}-${resourceType}')

output name string = resourceName('app',2, 'vnic')
Enter fullscreen mode Exit fullscreen mode

The function creates a name by concatenating parameters with ‘-‘

User-defined functions can't use variables and cannot use the reference function to retrieve.
They can only use one single expression, so it can be challenging to create a complex calculation. But you overcome this limitation by creating several user-defined functions, as you can call any other functions inside your functions.

func returnParam (myParam string) string  => '${myParam}'

func addPrefix (prefix string, appName string) string => concat(prefix, '-', returnParam(appName))

output name string = addPrefix('vm', 'web')
Enter fullscreen mode Exit fullscreen mode

You can’t surcharge a user-defined function by changing the type of a parameter or the number of parameters. You will get an error; Bicep will only try to evaluate the first expression. So, if you have an operation that can use several types you will need to use several functions.

Top comments (0)