User-defined functions in Bicep

Within your Bicep file, you can create your own functions. These functions are available for use in your Bicep files. User-defined functions are separate from the standard Bicep functions that are automatically available within your Bicep files. Create your own functions when you have complicated expressions that are used repeatedly in your Bicep files.

Bicep CLI version 0.26.X or higher is required to use this feature.

Limitations

When defining a user function, there are some restrictions:

  • The function can't access variables.
  • The function can only use parameters that are defined in the function.
  • The function can't use the reference function or any of the list functions.
  • Parameters for the function can't have default values.

Define the function

Use the func statement to define user-defined functions.

func <user-defined-function-name> (<argument-name> <data-type>, <argument-name> <data-type>, ...) <function-data-type> => <expression>

Examples

The following examples show how to define and use user-defined functions:

func buildUrl(https bool, hostname string, path string) string => '${https ? 'https' : 'http'}://${hostname}${empty(path) ? '' : '/${path}'}'

func sayHelloString(name string) string => 'Hi ${name}!'

func sayHelloObject(name string) object => {
  hello: 'Hi ${name}!'
}

func nameArray(name string) array => [
  name
]

func addNameArray(name string) array => [
  'Mary'
  'Bob'
  name
]

output azureUrl string = buildUrl(true, 'microsoft.com', 'azure')
output greetingArray array = map(['Evie', 'Casper'], name => sayHelloString(name))
output greetingObject object = sayHelloObject('John')
output nameArray array = nameArray('John')
output addNameArray array = addNameArray('John')

The outputs from the preceding examples are:

Name Type Value
azureUrl String https://microsoft.com/azure
greetingArray Array ["Hi Evie!","Hi Casper!"]
greetingObject Object {"hello":"Hi John!"}
nameArray Array ["John"]
addNameArray Array ["Mary","Bob","John"]

With Bicep CLI version 0.23.X or higher, you have the flexibility to invoke another user-defined function within a user-defined function. In the preceding example, with the function definition of sayHelloString, you can redefine the sayHelloObject function as:

func sayHelloObject(name string) object => {
  hello: sayHelloString(name)
}

User-defined functions support using user-defined data types. For example:

@minValue(0)
type positiveInt = int

func typedArg(input string[]) positiveInt => length(input)

param inArray array = [
  'Bicep'
  'ARM'
  'Terraform'
]

output elements positiveInt = typedArg(inArray)

The output from the preceding example is:

Name Type Value
elements positiveInt 3

Next steps