[英]In terraform, how to assign variable in a resource block only if condition matches
我試圖僅在條件匹配時才在塊中設置變量。
resource "teleport_role" "test_role" {
spec = {
allow = {
kubernetes_labels = {
"label_1" = "${local.some_var == "something" ? ["value_1"] : null}"
}
}
}
}
當條件false
時,在terrform plan
中我得到:
+ "label_1" = null
最終在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("")}).
簡而言之, null
不會讓label_1
被忽略。
如果條件為false
,我如何確保變量根本不被分配
例如,如果我必須在 Python 中這樣做,它會是這樣的:
if some_var == "something":
label_1 = value_1
參考: https://github.com/gravitational/teleport-plugins/issues/657
這是錯誤的,因為 Kube.netes 不允許在其 API 的規范模式中使用這種規范。go go-cty
似乎確實非常努力地將 HCL2/TF 類型強制轉換為與 Kube.netes 規范模式兼容的東西,所以他們的努力對他們有好處。
在大多數語言(包括這一語言)中,對於可枚舉/可迭代可能有未指定的值,那么未指定的需要為空而不是 nil/null/等等。
kubernetes_labels = local.some_var == "something" ? { "label_1" = ["value_1"] } : {}
go
無法為 Kube.netes 清單序列化它的可能性非常小(在這種情況下,條件需要位於更高的鍵),但這是 Terraform 中具體和一般實現此目的的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.