简体   繁体   English

terraform中,只有条件匹配时,如何在资源块中分配变量

[英]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:当条件false时,在terrform plan中我得到:

+ "label_1" = null

which eventually throws error during terraform apply :最终在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.简而言之, null不会让label_1被忽略。

How do I ensure that variable just don't get assigned at all if condition is false如果条件为false ,我如何确保变量根本不被分配

For example if I had to do it in Python, it would have been like:例如,如果我必须在 Python 中这样做,它会是这样的:

if some_var == "something":
   label_1 = value_1

Ref: https://github.com/gravitational/teleport-plugins/issues/657参考: 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.这是错误的,因为 Kube.netes 不允许在其 API 的规范模式中使用这种规范。go go-cty似乎确实非常努力地将 HCL2/TF 类型强制转换为与 Kube.netes 规范模式兼容的东西,所以他们的努力对他们有好处。

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.在大多数语言(包括这一语言)中,对于可枚举/可迭代可能有未指定的值,那么未指定的需要为空而不是 nil/null/等等。

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. go无法为 Kube.netes 清单序列化它的可能性非常小(在这种情况下,条件需要位于更高的键),但这是 Terraform 中具体和一般实现此目的的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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