如何在 Terraform 中列出列表中的所有项目,这里的 for 循环等效项是什么?



我是Terraform的新手,你能帮我处理Terraform中的列表吗。

这是我的代码

variable  "ip_bitbucket" {
type = "list"
}
ip_bitbucket = ["34.199.54.113/32","34.232.25.90/32","34.232.119.183/32","34.236.25.177/32","35.171.175.212/32","52.54.90.98/32","52.202.195.162/32","52.203.14.55/32","52.204.96.37/32","34.218.156.209/32","34.218.168.212/32","52.41.219.63/32","35.155.178.254/32","35.160.177.10/32","34.216.18.129/32","3.216.235.48/32","34.231.96.243/32","44.199.3.254/32","174.129.205.191/32","44.199.127.226/32","44.199.45.64/32","3.221.151.112/32","52.205.184.192/32","52.72.137.240/32"]

并且需要访问下面的列表

resource "aws_security_group_rule "server_rule" {
type              = "ingress"
from_port         = 443
to_port           = 22
protocol          = "tcp"
# for each = var.ip_bitbucket
cidr_blocks       = 
security_group_id = data.aws_security_group.server_sg.id
}

如何访问cidr块中的变量ip_bitbucket

我尝试了countelement,但没有弄清楚

您可以使用toset内置函数[1]:

resource "aws_security_group_rule "server_rule" {
for_each          = toset(var.ip_bitbucket)
type              = "ingress"
from_port         = 443
to_port           = 22
protocol          = "tcp"
cidr_blocks       = [each.value]
security_group_id = data.aws_security_group.server_sg.id
}

[1]https://developer.hashicorp.com/terraform/language/functions/toset

for_each参数需要一个映射值(具有任何元素类型)或一组字符串。您的输入变量当前被声明为列表,因此它与for_each不直接兼容。

ip_bitbucket中元素的顺序似乎没有意义,所以我认为最好的答案是将该变量的类型约束更改为set(string),这是对如何使用该值的更准确描述:

variable  "ip_bitbucket" {
type = set(string)
}

但是,您可以在单个安全组规则中指定多个CIDR块,因此您可能根本不需要for_each

resource "aws_security_group_rule" "server_rule" {
type              = "ingress"
from_port         = 443
to_port           = 22
protocol          = "tcp"
cidr_blocks       = var.ip_bitbucket
security_group_id = data.aws_security_group.server_sg.id
}

以上将声明一条适用于所有给定CIDR范围的规则。

如果您do仍然想使用for_each,那么一旦您如上所述更改了其类型约束,就可以使用var.ip_bitbucket作为for_each值:

resource "aws_security_group_rule" "server_rule" {
for_each = var.ip_bitbucket
type              = "ingress"
from_port         = 443
to_port           = 22
protocol          = "tcp"
cidr_blocks       = [each.value]
security_group_id = data.aws_security_group.server_sg.id
}

each.value的噪声需要放在括号中,因为each.value只是var.ip_bitbucket中的一个元素,所以它是一个单独的字符串。cidr_blocks需要一组字符串。

如果模块中未在此处显示的其他部分依赖于var.ip_bitbucket中元素的特定顺序,则可以将其声明为列表,然后将其转换为for_each参数内的集合。但是,只有当您确实需要保留这些元素的顺序时,我才会建议您这样做,因为如果您将其声明为列表,则模块的用户或未来维护者可能会认为顺序很重要。

variable  "ip_bitbucket" {
type = list(string)
}
resource "aws_security_group_rule" "server_rule" {
for_each = toset(var.ip_bitbucket)
type              = "ingress"
from_port         = 443
to_port           = 22
protocol          = "tcp"
cidr_blocks       = [each.value]
security_group_id = data.aws_security_group.server_sg.id
}

这与前面的示例相同,只是从列表到集合的转换是通过toset函数显式进行的,而不是在Terraform准备var.ip_bitbucket的值时自动进行的。

最新更新