Terraform workspace specific lines of code in Azure

77 Views Asked by At

I'm having an issue using terraform workspaces between a region pair. One workspace for South Central US and one for North Central US. Everything works great until it comes to zones. Public IP for example. South I’m setting zones, North won’t accept zone configuration empty, 0, or 1,2, or 3 because it doesn’t support zones yet. Hoping to set zones in SCU and eventually doing the same in NCU when they become available.

How do I use the same code in both regions? I know I can use workspace vars for values, but in this case it is an entire line of code. Seems like there should be an easy answer I’m just not thinking of.

Public IP code as an example below, but it the solution I would apply for VM deployments as well.

resource "azurerm_public_ip" "example" {
  name                = "acceptanceTestPublicIp1"
  resource_group_name = azurerm_resource_group.example.name
  location            = azurerm_resource_group.example.location
  allocation_method   = "Static"
  zones               = [1]

  tags = {
    environment = "Production"
  }
}
2

There are 2 best solutions below

1
On

@Mark B, you're brilliant! Such a simple answer that works. Bravo!

Here's an example of my variables.tfvars

firewalla-AvailabilityZone    = {
    hub-ncu        = null
    hub-scu        = [1]
}
firewallb-AvailabilityZone    = {
    hub-ncu        = null
    hub-scu        = [3]
}

Then in the resource:

zones = var.firewalla-AvailabilityZone[terraform.workspace]

2
On

You can check the terraform.workspace variable, and set the value to null if you don't want to set it to anything in a specific workspace:

zones    = terraform.workspace == "south" ? [1] : null

Change "south" to whatever the name of your Terraform workspace is that needs to set the zones value.