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 項目的完整範例範本,請參閱condition

執行階段函式

如果您在條件式部署的資源中使用 referencelist 函式,則即使不部署資源,也會評估該函式。 如果函式參考的資源不存在,您會收到錯誤。

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

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

完整模式

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

後續步驟