Terraform: Set optional resource attribute if condition is met, otherwise don't declare it

Viewed 3527

Some resources on Terraform support optional attributes. I'm interested in declaring and setting a value for the optional attribute only if a condition is met. Otherwise, don't declare it at all.

All of the suggestions I found was based on declaring the attribute and setting its value to null if the condition isn't satisfied, instead of not declaring the attribute at all.

Is there a way for me to do something like the following? In pseudo-code:

resource "some_resource" "this" {
  name = var.name

  if var.name == "some_name":
    some_optional_attribute = "some_value"
  else:
    pass  # do nothing, don't even declare the optional attribute
}

Let me know, thanks in advance!

1 Answers

I don't believe there is a better method than simply doing the following:

resource "some_resource" "this" {
  some_optional_attribute = var.name == "some_name" ? var.name : null
}

When you declare attribute as null that basically means that it is not being used. The above in my opinion is equivalent to your if statement.

Related