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

ARM 模板中的条件部署

有时,需要在 Azure 资源管理器模板(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",
      "defaultValue": true
    }
  },
  "functions": [],
  "resources": [
    {
      "condition": "[parameters('deployZone')]",
      "type": "Microsoft.Network/dnsZones",
      "apiVersion": "2023-07-01-preview",
      "name": "myZone",
      "location": "global",
      "properties": {
        "zoneType": "Public"
      }
    }
  ]
}

有关更复杂的示例,请参阅 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": "2025-06-01",
      "name": "[parameters('storageAccountName')]",
      "location": "[parameters('location')]",
      "sku": {
        "name": "Standard_LRS"
      },
      "kind": "StorageV2"
    },
    {
      "condition": "[equals(parameters('newOrExisting'), 'existing')]",
      "type": "Microsoft.Storage/storageAccounts",
      "apiVersion": "2025-06-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

运行时函数

如果将 引用列表 函数用于有条件部署的资源,则即使未部署资源,也会评估该函数。 如果函数引用的资源不存在,则会出现错误。

使用 if 函数确保仅在部署资源时评估该函数的条件。 查看 if 函数 来获取一个包含 ifreference 的条件部署资源的示例模板。

资源设置为依赖于 条件资源,就像任何其他资源一样。 如果未部署条件资源,Azure 资源管理器会自动将其从所需的依赖项中删除。

完整模式

如果部署了 具有完整模式 的模板,并且未部署资源,因为 condition 计算结果为 false,则结果取决于用于部署模板的 REST API 版本。 如果使用的版本早于 2019-05-10, 则不会删除该资源。 使用 2019-05-10 或更高版本时,资源 将被删除。 最新版本的 Azure PowerShell 和 Azure CLI 在条件为 false 时删除资源。

后续步骤