I’m creating my infra with terraform and I need to create a few security groups in AWS. I need to create multiple SG with this code:
resource "aws_security_group" "sg_ecs_app_service" {
for_each = local.mesh_resources
name = "${local.environment}-${local.workload_name}-ecs-${each.value.service_name}-service-sg"
description = "Security group for ${local.workload_name} ECS ${each.value.service_name} service"
vpc_id = local.vpc_id
ingress {
from_port = each.value.service_port
to_port = each.value.service_port
protocol = "tcp"
security_groups = [aws_security_group.sg_ecs_proxy_service.id]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
lifecycle {
create_before_destroy = true
}
tags = {
"Name" : "${local.environment}-${local.workload_name}-ecs-${each.value.service_name}-service-sg"
"environment" : local.environment
}
}
And I need to create another one like this:
resource "aws_security_group" "rds_sg" {
name = "${local.environment}-${local.workload_name}-rds-sg"
description = "Security group for ${local.workload_name} workload RDS database"
vpc_id = local.vpc_id
ingress {
from_port = 1521
to_port = 1521
protocol = "tcp"
security_groups = each.value.id
[
aws_security_group.sg_ecs_app_service[*].id
]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
lifecycle {
create_before_destroy = true
}
tags = {
"Name" : "${local.environment}-${local.workload_name}-rds-sg"
"environment" : local.environment
}
}
My issue is, in this last one SG, I don’t know how to add all the security groups created in the first code. With this example, I got an error.
How can I solve it?
2
Answers
If you want to reference all the security groups created with
for_each
in thesecurity_groups
argument of the RDS security group, you can do the following:By using the
values
built-in function, you will get all the security group IDs that you want to reference.Since you used
for_each
, you have to usevalues
in the second SG: So it should be: