ARM 範本中的使用者定義函式

在您的範本內,您可以建立自己的函式。 這些函式可供您在範本中使用。 使用者定義函式與範本中自動提供的標準範本函式不同。 若您有在範本中重複使用的複雜運算式,請建立您自己的函式。

本文說明如何在 Azure Resource Manager 範本 (ARM 範本) 中新增使用者定義函式。

定義函式

您的函式需要命名空間值,以避免範本函式發生命名衝突。 下列範例顯示可傳回唯一名稱的函式:

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

使用 函式

下列範例顯示包含使用者定義函式,可取得儲存體帳戶唯一名稱的範本。 範本有一個名為 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 的原因是您只能使用函式中定義的參數。 如需詳細資訊,請參閱限制
  • 在範本的 resources 區段中,name 元素會使用函式,並將 storageNamePrefix 值傳遞給函式的 namePrefix

限制

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

  • 此函式無法存取變數。
  • 此函式只能使用函式中定義的參數。 在使用者定義函式內使用 parameters 函式時會受到限制,只能使用該函式的參數。
  • 此函式無法呼叫其他的使用者定義函式。
  • 此函式無法使用 reference 函式或任何 list 函式。
  • 函式的參數不能有預設值。

下一步