你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

ARM 模板中的用户定义函数User-defined functions in ARM template

在模板中,可以创建自己的函数。 这些函数可在模板中使用。 用户定义的函数与模板中自动可用的 标准模板函数 是分开的。 当您有在模板中重复使用的复杂表达式时,请创建自己的函数。

本文介绍如何在 Azure 资源管理器模板(ARM 模板)中添加用户定义的函数。

定义函数

您的函数需要 namespace 值,以避免与模板函数发生命名冲突。 以下示例显示了一个返回唯一名称的函数:

"functions": [
  {
    "namespace": "contoso",
    "members": {
      "uniqueName": {
        "parameters": [
          {
            "name": "namePrefix",
            "type": "string"
          }
        ],
        "output": {
          "type": "string",
          "value": "[concat(toLower(parameters('namePrefix')), uniqueString(resourceGroup().id))]"
        }
      }
    }
  }
],

使用函数

以下示例显示了一个模板,该模板包含用于获取存储帐户的唯一名称的用户定义函数。 该模板具有一个名为 (name storageNamePrefix ) 的参数,该参数作为参数传递给函数。

{
 "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
 "contentVersion": "1.0.0.0",
 "parameters": {
   "storageNamePrefix": {
     "type": "string",
     "maxLength": 11
   }
 },
 "functions": [
  {
    "namespace": "contoso",
    "members": {
      "uniqueName": {
        "parameters": [
          {
            "name": "namePrefix",
            "type": "string"
          }
        ],
        "output": {
          "type": "string",
          "value": "[concat(toLower(parameters('namePrefix')), uniqueString(resourceGroup().id))]"
        }
      }
    }
  }
],
 "resources": [
   {
     "type": "Microsoft.Storage/storageAccounts",
     "apiVersion": "2022-09-01",
     "name": "[contoso.uniqueName(parameters('storageNamePrefix'))]",
     "location": "South Central US",
     "sku": {
       "name": "Standard_LRS"
     },
     "kind": "StorageV2",
     "properties": {
       "supportsHttpsTrafficOnly": true
     }
   }
 ]
}

在部署期间, storageNamePrefix 该参数将传递给函数:

  • 该模板定义了一个名为 storageNamePrefix.
  • 该函数使用 namePrefix 因为您只能使用函数中定义的参数。 有关详细信息,请参阅 “限制”。
  • 在模板的部分中 resourcesname 元素使用函数并将值传递给 storageNamePrefix 函数的 namePrefix.

局限性

定义用户函数时,存在一些限制:

  • 该函数不能访问变量。
  • 函数仅可使用函数中定义的参数。 当您在用户定义的函数中使用 parameters 函数时,您将被限制为该函数的参数。
  • 该函数不能调用其他用户定义的函数。
  • 该函数不能使用 reference 函数或任何 list 函数。
  • 该函数的参数不能具有默认值。

后续步骤