ARM 範本中的條件式部署 \(部分機器翻譯\)

有時您需要在 Azure Resource Manager 範本 (ARM 範本) 中選擇性部署資源。 請使用 condition 元素指定是否部署資源。 條件的值會解析為 true 或 false。 當此值為 true 時,會部署資源。 當此值為 false 時,則不會部署資源。 此值只能套用至整個資源。

注意

條件式部署不會串聯至子資源。 如果您想要有條件地部署資源及其子資源,必須將相同的條件套用至每個資源類型。

提示

我們建議使用 Bicep,因為其提供的功能與 ARM 範本相同,而且語法更易於使用。 若要深入了解,請參閱條件式部署

部署條件

您可以傳入參數值以指示是否部署資源。 下列範例顯示如何有條件地部署 DNS 區域。

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "deployZone": {
      "type": "bool"
    }
  },
  "functions": [],
  "resources": [
    {
      "condition": "[parameters('deployZone')]",
      "type": "Microsoft.Network/dnsZones",
      "apiVersion": "2018-05-01",
      "name": "myZone",
      "location": "global"
    }
  ]
}

如需更複雜的範例,請參閱 Azure SQL 邏輯伺服器

新的或現有的資源

您可以使用條件式部署建立新資源,或使用現有資源。 下列範例會示範如何部署新的儲存體帳戶,或使用現有的儲存體帳戶。

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "storageAccountName": {
      "type": "string"
    },
    "location": {
      "type": "string",
      "defaultValue": "[resourceGroup().location]"
    },
    "newOrExisting": {
      "type": "string",
      "defaultValue": "new",
      "allowedValues": [
        "new",
        "existing"
      ]
    }
  },
  "resources": [
    {
      "condition": "[equals(parameters('newOrExisting'), 'new')]",
      "type": "Microsoft.Storage/storageAccounts",
      "apiVersion": "2022-09-01",
      "name": "[parameters('storageAccountName')]",
      "location": "[parameters('location')]",
      "sku": {
        "name": "Standard_LRS"
      },
      "kind": "StorageV2"
    },
    {
      "condition": "[equals(parameters('newOrExisting'), 'existing')]",
      "type": "Microsoft.Storage/storageAccounts",
      "apiVersion": "2022-09-01",
      "name": "[parameters('storageAccountName')]"
    }
  ],
  "outputs": {
    "storageAccountId": {
      "type": "string",
      "value": "[if(equals(parameters('newOrExisting'), 'new'), resourceId('Microsoft.Storage/storageAccounts', parameters('storageAccountName')), resourceId('Microsoft.Storage/storageAccounts', parameters('storageAccountName')))]"
    }
  }
}

當參數 newOrExisting 設為 new 時,條件會評估為 true。 系統便會部署儲存體帳戶。 否則會使用現有的儲存體帳戶。

如需使用 condition 項目的完整範例範本,請參閱 使用新的或現有的虛擬網路、儲存體和公用 IP 的 VM

執行階段函式

如果您在條件式部署的資源中使用 referencelist 函式,則即使不部署資源,也會評估該函式。 如果該函式參照不存在的資源,便會發生錯誤情形。

請使用 if 函式,確保只有部署資源時才會評估條件。 如需對條件式部署的資源搭配使用 ifreference 的範例範本,請參閱 if 函式

您可以設定資源相依於條件式資源,就像任何其他資源一樣。 如果未部署條件式資源,Azure Resource Manager 會自動將其從必要的相依性中移除。

完整模式

如果您使用完整模式部署範本,卻因為 condition 評估為 false 而未部署資源,則結果取決於您用來部署範本的 REST API 版本。 如果您使用的版本早於 2019-05-10,則不會刪除資源。 使用 2019-05-10 或更新版本時,會刪除資源。 當條件為 false 時,Azure PowerShell 和 Azure CLI 的最新版本會刪除資源。

下一步