How to ommit optional block in terrafrom resource based on input variable
How to ommit optional block in terrafrom resource based on input variable
The goal is to create azurerm_virtual_hub_connection which might or might not have an optional block called static_vnet_route section under routing {} block.
File variables.tf
1
2
3
4
5
variable "static_vnet_routes" {
  description = "Static routes for virtual network connection"
  type        = list(any)
  default     = []
}
File terrafrom.tfvars
1
2
3
4
5
6
7
8
9
10
11
12
static_vnet_routes = [
    #{
    #  name = "static_route_1"
    #  address_prefixes = ["10.0.2.0/24"]
    #  next_hop_ip_address = "10.0.1.2"
    #},
    #{
    #  name = "static_route_2"
    #  address_prefixes = ["10.0.3.0/24"]
    #  next_hop_ip_address = "10.0.1.4"
    #}
]
And finally azurerm_virtual_hub_connection resource looks like following:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
resource "azurerm_virtual_hub_connection" "vhub_connection" {
  name                      = var.vhub_connection_name
  virtual_hub_id            = var.virtual_hub_id
  remote_virtual_network_id = azurerm_virtual_network.vnet.id
  routing {
      # static_vnet_route {}
      dynamic "static_vnet_route" {
        for_each = length(var.static_vnet_routes) > 0 ? var.static_vnet_routes : tolist(
          [
            {
              name = null
              address_prefixes = null
              next_hop_ip_address = null
            }
          ]
        )
        iterator = static_route
        content {
          name                = static_route.value.name
          address_prefixes    = static_route.value.address_prefixes
          next_hop_ip_address = static_route.value.next_hop_ip_address
        }
      }
  }
}
 This post is licensed under  CC BY 4.0  by the author.
