如何使用 terraform 有条件地跳过一部分 terraform 资源而不是 created/implemented

How to conditionally skip a part of terraform resource from being created/implemented using terrraform

如何使用 terraform 有条件地跳过一部分 terraform 资源created/implemented?

# main.tf file
locals {
  vnet_type = (var.vnet_type != "" ? var.vnet_type : "None")
}

data "azurerm_virtual_network" vnet {
  name = "testvnet"
  resource_group_name = "rest1"
}
  
data "azurerm_subnet" subnets {
  name = "testSubnet"
   resource_group_name  = "rest1"
   virtual_network_name = data.azurerm_virtual_network.vnet.name

}


resource "azurerm_api_management" "apim_demo" {
  name                = "test-apim"
  location            = "East US"
  resource_group_name = "rest1"
  publisher_name      = "admin"
  publisher_email     = "admin@gmail.com"

  sku_name = "Developer_1"

  identity {
    type = "SystemAssigned"
  }

 # vnet_Type can be External, None or Internal
 virtual_network_type = local.vnet_type
virtual_network_configuration {
  subnet_id = data.azurerm_subnet.subnets.id
}

}

# variables.tf file
variable "vnet_type" {}

# terraform.tfvars file
vnet_type = "External"

我有三个(dev、stg 和 prod)环境,我想在其中应用以下 block/part 的 tf 代码到 dev 和 stg 环境,对于 prod 环境跳过它。

如何使用条件表达式或 terraform 中的东西实现上述场景?

 virtual_network_type = local.vnet_type
virtual_network_configuration {
  subnet_id = data.azurerm_subnet.subnets.id
}

通常你会使用 null and dynamic blocks:

virtual_network_type = var.env == "prod" ? local.vnet_type : null


dynamic "virtual_network_configuration" {
   for_each = var.env == "prod" ? [1] : []
   content {
     subnet_id = data.azurerm_subnet.subnets.id
   }
}