7

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!

Adler Santos
  • 365
  • 5
  • 19

1 Answers1

4

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.

marcincuber
  • 3,451
  • 1
  • 17
  • 29
  • 1
    Some resources were previously created without that optional attribute being declared. The provider requires a destroy/create action if we simply declare the optional attribute and set it to `null`. Using your ternary example, `terraform plan` says `Plan: 10 to add, 0 to change, 10 to destroy`. Unfortunately, destroying those resources isn't an option for us. – Adler Santos Apr 09 '20 at 19:47
  • 2
    It'd be nice though if Terraform can "assume" that optional attributes that are declared and set to `null` is equivalent to optional attributes that weren't declared in the first place, when comparing with the remote state. – Adler Santos Apr 09 '20 at 19:50
  • Yeah, there is definitely no other way, unless you directly modify the state file and add the additional attribute to the resource and set it to null there. Not the best way but it worked for me. Note that I am personally against modifying states directly. – marcincuber Apr 09 '20 at 20:03
  • 3
    Internally within Terraform there is no difference between an argument set explicitly to `null` and one just left unset: provider logic cannot see the difference in order to make distinctions based on it. The only case I'd expect to see Terraform plan a change for this is if the condition expression produces a value that can't be known until apply, and thus Terraform must conservatively assume that the value will change, but that seems unlikely for this hypothetical `var.name`. If you ask a _new_ question about why Terraform is detecting a change in your case, I might be able to explain it. – Martin Atkins Apr 10 '20 at 00:08