[英]Conditional Expression not working in aws_security_group resource egress block terraform
for resource aws_security_group , i want to add egress block to run only if ingress rules are created.对于资源 aws_security_group ,我想添加出口块以仅在创建入口规则时运行。 Below i have applied condition for the egress block using count then tried with for_each , but I am getting error : An argument named "count" or "for_each" is not expected here respectively.
下面我使用 count 为 egress 块应用了条件,然后尝试使用 for_each ,但我收到错误:这里分别不需要名为“count”或“for_each”的参数。 Can someone please help how can i achieve this
有人可以帮助我如何实现这一目标
code代码
egress {
#for_each = (length(split(",", var.ingress_ports_udp)) != 0 && length(split(",", var.ingress_ports_udp)) != 0) ? ["1"] : []
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
You're looking for the dynamic block .您正在寻找动态块。 It would look something like this:
它看起来像这样:
resource "aws_security_group" "mygroup" {
name = "mygroup"
vpc_id = aws_vpc.main.id
dynamic "egress" {
for_each = (condition) ? [1] : []
content {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}
}
Your condition looks quite odd.你的情况看起来很奇怪。 First off, you're checking exactly the same condition twice (
length(split(",", var.ingress_ports_udp)) != 0
appears to be duplicated), and second, split
will never return a list of length 0 anyways (if an empty string is given, it will return a list with one element, which is itself an empty string).首先,您要检查两次完全相同的条件(
length(split(",", var.ingress_ports_udp)) != 0
似乎是重复的),其次, split
永远不会返回长度为 0 的列表(如果给出一个空字符串,它将返回一个包含一个元素的列表,它本身就是一个空字符串)。 You can see this on the split documentation page , third example:您可以在拆分文档页面上看到这一点,第三个示例:
> split(",", "")
[
"",
]
So your condition will never be false
, no matter what the value of var.ingress_ports_udp
is.所以你的条件永远不会是
false
,无论var.ingress_ports_udp
的值是什么。 You can use compact(split(",", var.ingress_ports_udp))
to deal with this ( compact will remove any list elements that are empty strings).您可以使用
compact(split(",", var.ingress_ports_udp))
来处理这个问题( compact将删除任何为空字符串的列表元素)。
I'd recommend passing var.ingress_ports_udp
in as a list of numbers, instead of as a string that you split within the module.我建议将
var.ingress_ports_udp
作为数字列表传入,而不是作为在模块中拆分的字符串。 Then you can simply use length(var.ingress_ports_udp) > 0 ? [1] : []
然后你可以简单地使用
length(var.ingress_ports_udp) > 0 ? [1] : []
length(var.ingress_ports_udp) > 0 ? [1] : []
. length(var.ingress_ports_udp) > 0 ? [1] : []
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.