Hello,
I would like to create a security group with a count condition like this:
resource "aws_security_group" "sg" {
count = var.autoscaling ? 0 : 1
name = "${var.env}.test.sg"
description = "test sg"
vpc_id = var.vpc_id
tags = {
Name = "${var.env}.test.sg"
ResourceType = "sg"
}
}
When autoscaling is set to false however I cannot handle the corresponding SG rules that I load with for_each like this:
resource "aws_vpc_security_group_egress_rule" "sgrules_out" {
for_each = { for rule in var.sgrules_outbound : rule.rule_name => rule }
cidr_ipv4 = each.value.cidr_blocks
description = each.value.description
from_port = each.value.from_port
to_port = each.value.to_port
ip_protocol = each.value.protocol
security_group_id = aws_security_group.sg.*.id
tags = {
Name = "${var.env}.test.sg"
ResourceType = "Infra_Network"
}
}
sg.tfvars:
sgrules_outbound = [
{
rule_name = "test"
cidr_blocks = ["192.168.1.0/24"]
description = "test"
from_port = 1500
protocol = "tcp"
to_port = 1500
}
]
Error I get is:
Error: Incorrect attribute value type
on sg_efs.tf line 32, in resource "aws_vpc_security_group_egress_rule" "sgrules_out":
32: security_group_id = aws_security_group.sg.*.id
├────────────────
│ aws_security_group.sg is tuple with 1 element
Inappropriate value for attribute "security_group_id": string required.
Is there a way to handle these rules when the SG’s condition is false and therefore it shouldn’t create it? I know count and for_each are not supported together, unfortunately.