Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terraform: Create block only if variable matches certain values

Tags:

terraform

I'm trying to create a module that creates interconnect-attachments, but some parts are only defined if the attachment is using ipsec encryption and if it's not, that block must not exist in the resource else it causes an error (even if it only contains a value set to null.) I've tried using a dynamic, but I can't quite get the layout right to have it work:

resource "google_compute_interconnect_attachment" "interconnect-attachment" {
  project                  = var.project
  region                   = var.region
  name                     = var.name
  edge_availability_domain = var.availability_domain
  type                     = var.type
  router                   = google_compute_router.router.name
  encryption               = var.encryption
  dynamic "ipsec_internal_addresses" {
    for_each = var.encryption != "IPSEC" ? [] : [1]
    content {
      var.address
    }
  }
}

Essentially, if var.encryption is set to IPSEC then i want the following block included:

  ipsec_internal_addresses = [
    var.address,
  ]

The other issue is it appears a dynamic block expects some kind of assignment to happen, but the terraform examples just have the value inside the ipsec_internal_addresses so I'm unsure how to to achieve this.

like image 786
djsmiley2kStaysInside Avatar asked Nov 24 '25 07:11

djsmiley2kStaysInside


1 Answers

ipsec_internal_addresses is not a block in the google_compute_interconnect_attachment resource. It is an argument. Therefore, you can use the normal pattern for specifying optional arguments where the conditional returns a null type if you do not want to specify a value. Using your conditional and variables:

ipsec_internal_addresses = var.encryption == "IPSEC" ? [var.address] : null

which will return and assign your [var.address] to ipsec_internal_addresses when var.encryption equals the string IPSEC. Otherwise, it will return null and the ipsec_internal_addresses argument will be ignored.

like image 162
Matt Schuchard Avatar answered Nov 27 '25 01:11

Matt Schuchard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!