我一直在为 AWS 基础设施编写可重用的模块。在创建安全组时,我的方法是为安全组创建一个通用模块,并在控制代码中提供端口列表。但是,使用count
时,它会为每个端口创建一个安全组。有没有办法像在这种情况下那样迭代特定部分?
SG 模块
resource "aws_security_group" "this" {
name = var.sg_name
description = var.description
vpc_id = var.vpc_id
count = min(length(var.ingress_ports))
ingress {
from_port = var.ingress_ports[count.index]
to_port = var.ingress_ports[count.index]
protocol = "tcp"
cidr_blocks = ["10.0.0.0/8"]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}
控制代码
module "qliksense_sg" {
source = "modules/aws-sg"
sg_name = "My-SG"
description = "A security group"
vpc_id = module.vpc.vpc_id
ingress_ports = ["80", "443"]
}
要在Terraform 0.12中执行此操作,您可以使用dynamic
块。实际上,该文档链接中给出的示例用于在端口列表上添加入口规则:
resource "aws_security_group" "example" {
name = "example" # can use expressions here
dynamic "ingress" {
for_each = var.service_ports
content {
from_port = ingress.value
to_port = ingress.value
protocol = "tcp"
}
}
}