问题描述
我有一个场景,我需要创建属于集群一部分的多个EC2实例,这些主机必须可以在特定端口上相互访问,并且需要连接两个ebs_volumes大小为16GB和700GB。 我的variable.tf的片段如下所示:-
variable "instances" {
default = {
instance_name = "a"
tcp_ports = ["53","22","2022","80","443"]
udp_ports = ["53","67","68","123","161","162","500"]
"xvdf" = "16"
"xvdg" = "700"
}
}
我正在努力使此映射与我的TF脚本一起使用:-
resource "aws_security_group_rule" "tcp_ingress" {
for_each = {
for inst in local.instances : inst.tcp_ports => {
for i in inst: i.tcp_ports => i
}
}
type = "ingress"
from_port = each.value.tcp_ports
to_port = each.value.tcp_ports
protocol = "tcp"
cidr_blocks = [ for i in aws_instance.instance: format("%s/32",i.private_ip ) ]
security_group_id = aws_security_group.ha-sg.id
}
有没有一种方法可以遍历端口并形成安全组规则。
解决方法
有没有一种方法可以遍历端口并形成安全组规则。
由于您的variable "instances"
是一张地图,要访问tcp_ports
,您只需执行以下操作:
var.instances.tcp_ports
然后在for_each
中使用它:
resource "aws_security_group_rule" "tcp_ingress" {
for_each = toset(var.instances.tcp_ports)
type = "ingress"
from_port = each.value
to_port = each.value
protocol = "tcp"
cidr_blocks = [ for i in aws_instance.instance: format("%s/32",i.private_ip ) ]
security_group_id = aws_security_group.ha-sg.id
}