How to conditionally skip a part of terraform resource from being created/implemented using terraform?
# 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 = "[email protected]"
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"
I have three (dev, stg and prod) environments where I want to apply below block/part of tf code to dev & stg environments skip it for prod environment.
How do I achieve above scenario using conditional expression or something in terraform ?
virtual_network_type = local.vnet_type
virtual_network_configuration {
subnet_id = data.azurerm_subnet.subnets.id
}
CodePudding user response:
Generally you would use 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
}
}