terraform 中是否有 AND/OR 条件运算符? [英] Is there a way AND/OR conditional operator in terraform?
问题描述
有没有办法在 Terraform 中使用类似的东西?
Is there a way to use something like this in Terraform?
count = "${var.I_am_true}"&&"${var.I_am_false}"
count = "${var.I_am_true}"&&"${var.I_am_false}"
推荐答案
deniszh 的答案非常接近,但我想我会澄清一下并清理语法.
The answer by deniszh is pretty close, but I thought I'd clarify it a bit and clean up the syntax.
在 Terraform 中,布尔值 true
被转换为 1
,布尔值 false
被转换为 0
.因此,如果您有两个布尔变量,var.foo
和 var.bar
,您可以使用简单的乘法表示 AND
:
In Terraform, a boolean true
is converted to a 1
and a boolean false
is converted to a 0
. So if you have two boolean variables, var.foo
and var.bar
, you can represent AND
using simple multiplication:
count = "${var.foo * var.bar}"
在上面的代码中,只有当 var.foo
AND var.bar
都为 true时,
count
才会为 1code>,因为 1 * 1 是 1.在所有其他情况下 (1 * 0, 0 * 1, 0 * 0),你得到 0.
In the code above, count
will be 1 only if var.foo
AND var.bar
are both true
, as 1 * 1 is 1. In all other cases (1 * 0, 0 * 1, 0 * 0), you get 0.
要表示 OR,您可以利用函数 signum(x),如果你传入的 x
是正数则返回 1,如果 x
为 0 则返回 0,如果 x
则返回 -1是一个负数.考虑到这一点,这里是 OR:
To represent OR, you can take advantage of the function signum(x), which returns 1 if the x
you pass in is a positive number, 0 if x
is 0, and -1 if x
is a negative number. Taking this into account, here is OR:
count = "${signum(var.foo + var.bar)}"
在上面的代码中,如果 var.foo
或 var.bar
为 true
count 将为 1> 和 0 仅当两者都是 false
(signum(1 + 1) = 1
, signum(1 + 0) = 1
, signum(0 + 1) = 1
, signum(0 + 0) = 0
).
In the code above, count
will be 1 if either var.foo
OR var.bar
is true
and 0 only if both are false
(signum(1 + 1) = 1
, signum(1 + 0) = 1
, signum(0 + 1) = 1
, signum(0 + 0) = 0
).
请注意,要使用上述技术,您必须注意将变量设置为布尔值而不是字符串.你想要这个:
Note that to use the techniques above, you must take care to set the variables to a boolean and NOT a string. You want this:
variable "foo" {
# Proper boolean usage
default = true
}
不是这个:
variable "foo" {
# THIS WILL NOT WORK!
default = "true"
}
有关如何执行各种 Terraform 条件的更多信息,请查看 Terraform 提示 &技巧:循环、if 语句和陷阱 和 Terraform: Up &正在运行.
For more info on how to do a variety of Terraform conditionals, check out Terraform tips & tricks: loops, if-statements, and gotchas and Terraform: Up & Running.
这篇关于terraform 中是否有 AND/OR 条件运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!