1
votes

Given this resource:

resource "google_compute_instance" "instance" {
    ...
    network_interface {
        ...
        access_config {
            ...
        }
    }
}

I'd like to conditionally define the access_config property based on a condition.

[Edit] Solution

resource "google_compute_instance" "instance" {
    ...
    network_interface {
        ...
        dynamic "access_config" {
            for_each = var.condition ? [1] : []
            content {
                ...
            }
        }
    }
}
2
Could you please update with the results of your dynamic nested block? Also, this may end up being an issue on the Terraform Github tracker. - Matt Schuchard
Actually I discovered that the syntax that I wrote is correct! My IDE was simply complaining and I assumed there was something wrong... my bad! - rickyalbert

2 Answers

1
votes

Similar to what Josep Nadal mentioned, but change count to for_each like

  dynamic "access_config" {
    for_each = var.conditional_on ? ["1"] : []
    content {
      nat_ip = null
    }
  }
0
votes

I am not really familiar, but I think you can accomplish this using the count parameter.

First you need to add a variable into your variables.tf file:

variable "conditional_on" {
  description = "enable or disable"
  type        = bool
}

Then you can add the count parameter with the variable:

resource "google_compute_instance" "instance" {
    ...
    network_interface {
        ...
        dynamic "access_config" {
            count = var.conditional_on ? 1 : 0
            content {
                ...
            }
        }
    }
}

There is more information on the Terraform Documentation: https://www.terraform.io/docs/configuration-0-11/interpolation.html#conditionals