英文:
Terraform: Local variable reference
问题
我有类似如下的东西:
locals {
   a = var.from_scratch
   b = a == "true"? 5 : 56
}
显然,这不是有效的Terraform语法。我无法在决定b的条件中使用a。这是一个非常简单的例子,但对于更复杂的表达式,例如a的评估更复杂,这将非常有用。在Terraform中是否有任何方法可以做到这一点?我得到Invalid reference错误。
英文:
I have something like so:
locals {
   a = var.from_scratch
   b = a == "true"? 5 : 56
}
Apparently, this is not a valid Terraform syntax. I cannot use a on the condition that decides b. This is a very simple example but this would be very handy for more complex expression e.g. the evaluation of a is more involved. Is there any way to do that in Terraform? I get Invalid reference.
答案1
得分: 1
你必须在 locals 区块中明确指定 local:
locals {
   a = var.from_scratch
   b = local.a == "true" ? 5 : 56
}
但请记住,目前你正在将 local.a 与字面值 "true" 进行比较,而你可能只想要布尔值 true:
locals {
   a = var.from_scratch
   b = local.a == true ? 5 : 56
}
英文:
You have to specify local even in the locals block:
locals {
   a = var.from_scratch
   b = local.a == "true"? 5 : 56
}
but do keep in mind that currently you are comparing local.a to a literal "true", whereas you probably just want the boolean true.
locals {
   a = var.from_scratch
   b = local.a == true ? 5 : 56
}
答案2
得分: 1
The code can be modified like this:
locals {
   b = var.from_scratch ? 5 : 56
}
As a side note, unless you have defined the from_scratch variable as a string, the comparison from your question will not work. There is also a bool type in Terraform, so you should use that instead of using a variable of type string and setting it to "true."
英文:
Unless you plan on using the local a variable elsewhere in the code, the code can be modified like this:
locals {
   b = var.from_scratch ? 5 : 56
}
As a side note, unless you have defined the from_scratch variable as string, the comparison from your question will not work. There is also bool type in terraform, so you should use that instead of using a variable of type string and setting it to "true".
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论