Search code examples
google-cloud-platformterraformterraform-provider-gcp

Terraform: Conditionally include an attribute of a resource


Quite new to terraform and I have an issue.

I'm going the 'google_compute_image' resource to look up an image - my module needs to do this by image name OR image family. 1 or the other and not both.

When one is provided the other is empty.

Currently I have something like this

data "google_compute_image" "my_image_from_family" {
  family  = var.image_family
  project = "my project"
}

data "google_compute_image" "my_image_from_name" {
  name    = var.image
  project = "my project"
}

module "my module" {
    ...
    image = var.image == "" ? data.google_compute_image.my_image_from_family.self_link : data.google_compute_image.my_image_from_name.self_link
}

When one of either image or image_family is specified the other data resource fails because it says something like 'one of name, family or filter is required'

My understanding is that the data resource wouldn't even be evaluated if not needed, but that seems to be wrong.

What I'd like to do is something like (those familiar with chef might recognise the idea)

data "google_compute_image" "my_image_from_family" {
  family  = var.image_family if var.image_family != ""
  name    = var.image if var.image != ""
  project = "my project"
}

But this doesn't seem possible.

Can anyone help with a solution here?

Thanks


Solution

  • What you could do is the following:

    data "google_compute_image" "my_image_from_family" {
      family  = var.image_family != "" ? var.image_family : null
      name    = var.image != "" ? var.image : null
      project = "my project"
    }
    

    This is the ternary operator in terraform [1].


    [1] https://developer.hashicorp.com/terraform/language/expressions/conditionals#syntax