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 Kubernetes 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 Kubernetes 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.
There is a very small chance that
go
will be unable to serialize that for the Kubernetes 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.