3

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. Commented Oct 2, 2019 at 16:10
  • 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! Commented Oct 3, 2019 at 7:22

2 Answers 2

5

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
    }
  }
Sign up to request clarification or add additional context in comments.

Comments

-1

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

3 Comments

Either I am missing something or dynamic blocks don't support count
did anyone found answer for this ?
for me only works with for each, not with count

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.