Context
Let’s say you want to include a terraform resource block in your infrastructure configuration files only when a Terraform variable has a specific value. In my use case, we want to deploy a disaster recovery azure virtual network only on the production environment. However, we want to keep our terraform code iso prod, which means that we use the same configuration files for all environments: development, uat and prod.
Conditional terraform resource block
We use the value of the variable TF_VAR_ENV to decide whether Terraform will process this Disaster Recovery Virtual Network or not. The count operator allows you to do just that.
resource "azurerm_virtual_network" "DRvnetspoke" {
count = var.ENV == "prod" ? 1 : 0
name = "vnet-spoke-${var.APPNAME}-DR-${var.ENV}"
location = var.LOCATION
resource_group_name = azurerm_resource_group.networkspokerg.name
address_space = [var.VNETSPOKESPACEDR]
tags = var.DEFAULTTAGS
}
In your deployment pipeline this block will be ignored for the non-prod environments, which will allow you to use the same code for all of them.
You can also base your condition on multiple expressions, again with the same count operator.
resource "azurerm_virtual_network" "DRvnetspoke" {
count = (var.WITHDR == "true" && var.ENV == "prod") ? 1 : 0
...
}