[英]Terraform - Iterate and create Ingress Rules for a Security Group
I've been writing reusable modules for an AWS infrastructure.我一直在为 AWS 基础设施编写可重用的模块。 In creating a security group, my approach is to create a generic module for a security group and provide a list of ports in the control code.
在创建安全组时,我的方法是为安全组创建一个通用模块并在控制代码中提供端口列表。 However, when using
count
it creates a security group each for every port.但是,当使用
count
它会为每个端口创建一个安全组。 Is there a way around this to iterate a specific part like in this scenario?有没有办法像在这种情况下那样迭代特定部分?
SG Module 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"]
}
}
Control Code控制代码
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"]
}
To do this in Terraform 0.12 you can use dynamic
blocks .要在 Terraform 0.12 中做到这一点,您可以使用
dynamic
块。 In fact, the example given in that documentation link is for adding ingress rules over a list of ports:事实上,该文档链接中给出的示例用于在端口列表上添加入口规则:
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"
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.