简体   繁体   中英

In terraform, how to assign variable in a resource block only if condition matches

I am trying to set a variable in a block only if a condition matches.

resource "teleport_role" "test_role" {
  spec = {
    allow = {
      kubernetes_labels = {
        "label_1" = "${local.some_var == "something" ? ["value_1"] : null}"
      }
    }
  }
}

When a false condition, in terrform plan I get:

+ "label_1" = null

which eventually throws error during terraform apply :

│ When applying changes to teleport_role. test_role, provider
│ "provider[\"terraform.releases.teleport.dev/gravitational/teleport\"]"
│ produced an unexpected new value:
│ .spec.allow.kubernetes_labels["label_1"]: was null, but now
│ cty.ListVal([]cty.Value{cty.StringVal("")}).

In nutshell, null doesn't let label_1 be ignored.

How do I ensure that variable just don't get assigned at all if condition is false

For example if I had to do it in Python, it would have been like:

if some_var == "something":
   label_1 = value_1

Ref: https://github.com/gravitational/teleport-plugins/issues/657

This is erroring because Kube.netes does not allow this kind of specification in its spec schema for that API. go-cty does seem to be trying really hard to coerce that HCL2/TF type into something compatible with Kube.netes spec schema, so good on them for that effort.

In most languages (this one included) with potentially unspecified values for enumerables/iterables, then the unspecified needs to be empty instead of nil/null/etc.

kubernetes_labels = local.some_var == "something" ? { "label_1" = ["value_1"] } : {}

There is a very small chance that go will be unable to serialize that for the Kube.netes manifest (in which case the conditional needs to be at a higher key), but this is code for how to achieve this specifically and generally in Terraform.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM