Terraform:使用 for_each 和映射 security_group_rule 使用 Terraform 创建多个实例
Terraform: Creating multiple instances with Terraform with for_each and mapping security_group_rule
我有一个场景,我需要创建多个 EC2 实例,这些实例是 cluster.These 主机的一部分,必须可以在特定端口上相互访问,并且需要连接两个 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
}
有什么方法可以遍历端口并形成安全组规则。
Is there a way I can iterate through the ports and form the security group rules.
由于您的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
}
我有一个场景,我需要创建多个 EC2 实例,这些实例是 cluster.These 主机的一部分,必须可以在特定端口上相互访问,并且需要连接两个 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
}
有什么方法可以遍历端口并形成安全组规则。
Is there a way I can iterate through the ports and form the security group rules.
由于您的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
}