terraform

How do I make a block optional in a module?


I have this resource in my module: https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/compute_router

I merely want to make advertised_ip_ranges optional via a variable.

I my module I do this:

resource "google_compute_router" "my-router" {
  .....
  bgp {
    .....
    advertised_ip_ranges = var.advertised_ip_ranges

I tried the following, but nothing is working

I just want to be able to ignore and not set advertised_ip_ranges via the variable.


Solution

  • You can set it based on a variable, but you'll need to use dynamic.

    For example:

    variable "advertised_ip_ranges" {
      type    = set(map(string))
      default = []
    
      # Requires Terraform 1.1+
      # Other option is to default to `null`, and add check in `dynamic`.
      nullable = false
    }
    
    resource "google_compute_router" "my_router" {
      bgp {
        dynamic "advertised_ip_ranges" {
          for_each = var.advertised_ip_ranges
          # Without `nullable`:
          # for_each = coalesce(var.advertised_ip_ranges, [])
    
          content {
            # Mandatory
            range = advertised_ip_ranges.value.range
            # Optional
            description = lookup(advertised_ip_ranges.value, "description", null)
          }
        # ...
      }
      # ...
    }