分享方式:


Bicep 中的使用者定義函式

在您的 Bicep 檔案中,您可以建立自己的函式。 這些函式可用於 Bicep 檔案。 用戶定義的函式與 Bicep 檔案中自動可用的標準 Bicep 函式不同。 若您有在 Bicep 檔案中重複使用的複雜運算式,請建立您自己的函式。

需要 Bicep CLI 0.26.X 版或更高版本 才能使用此功能。

限制

在定義使用者函式時,有一些限制:

  • 此函式無法存取變數。
  • 此函式只能使用函式中定義的參數。
  • 此函式無法使用 reference 函式或任何 list 函式。
  • 函式的參數不能有預設值。

定義函式

func使用語句來定義使用者定義函數。

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

範例

下列範例示範如何定義及使用使用者定義函式:

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')

上述範例的輸出如下:

名稱 類型
azureUrl String https://microsoft.com/azure
greetingArray 陣列 [“Hi Evie!”,“Hi Casper!”]
greetingObject Object {“hello”:“Hi John!”}
nameArray 陣列 [“John”]
addNameArray 陣列 [“Mary”,“Bob”,“John”]

透過 Bicep CLI 0.23.X 版或更高版本,您可以彈性地叫用使用者定義函式內的另一個使用者定義函式。 在上述範例中,使用的 sayHelloString函式定義,您可以將 函 sayHelloObject 式重新定義為:

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

使用者定義函數支援使用 使用者定義的數據類型。 例如:

@minValue(0)
type positiveInt = int

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

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

output elements positiveInt = typedArg(inArray)

前述範例的輸出為:

名稱 類型
項目 positiveInt 3

下一步

  • 若要瞭解 Bicep 檔案結構和語法,請參閱 瞭解 Bicep 檔案的結構和語法。
  • 如需可用 Bicep 函式的清單,請參閱 Bicep 函式