Skip to content

Commit c75f8d4

Browse files
authored
Fixes "Error: no association of default Security Group (sg-XXX) with VPC Endpoint (vpce-YYY)" (#158)
* Update main.tf Update * Update main.tf * Update main.tf * Update main.tf * Update main.tf Formatting. * Update main.tf
1 parent 1f578f3 commit c75f8d4

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

modules/vpc-endpoints/main.tf

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,24 @@ locals {
2323

2424
subnet_associations_map = { for v in local.subnet_associations_list : v.key => v }
2525

26+
# Build a list of SG associations for SGs with index > 0 only.
27+
# We skip index 0 because that SG is already attached at creation time,
28+
# so there's no need to manage it via a separate association resource.
29+
security_group_associations_list = flatten([
30+
for k, v in var.interface_vpc_endpoints : [
31+
for i, s in v.security_group_ids : i == 0 ? [] : [{
32+
key = "${k}[${i}]"
33+
index = i
34+
interface = k
35+
security_group_id = s
36+
}]
37+
]
38+
])
39+
40+
# Map of the above list, keyed by "endpoint[index]" format for easy for_each iteration.
41+
security_group_associations_map = {
42+
for v in local.security_group_associations_list : v.key => v
43+
}
2644
}
2745

2846
data "aws_vpc_endpoint_service" "gateway_endpoint_service" {
@@ -82,7 +100,11 @@ resource "aws_vpc_endpoint" "interface_endpoint" {
82100
vpc_id = var.vpc_id
83101
private_dns_enabled = var.interface_vpc_endpoints[each.key].private_dns_enabled
84102

85-
security_group_ids = length(var.interface_vpc_endpoints[each.key].security_group_ids) > 0 ? var.interface_vpc_endpoints[each.key].security_group_ids : null
103+
# Attach the first security group *at creation time* so AWS never attaches the default SG.
104+
# This avoids the need to "replace_default_association", which can fail on later applies.
105+
security_group_ids = length(var.interface_vpc_endpoints[each.key].security_group_ids) > 0 ? [
106+
var.interface_vpc_endpoints[each.key].security_group_ids[0]
107+
] : []
86108

87109
tags = module.interface_endpoint_label[each.key].tags
88110
}
@@ -93,3 +115,12 @@ resource "aws_vpc_endpoint_subnet_association" "interface" {
93115
subnet_id = each.value.subnet_id
94116
vpc_endpoint_id = aws_vpc_endpoint.interface_endpoint[each.value.interface].id
95117
}
118+
119+
resource "aws_vpc_endpoint_security_group_association" "interface" {
120+
for_each = local.enabled ? local.security_group_associations_map : {}
121+
122+
security_group_id = each.value.security_group_id
123+
vpc_endpoint_id = aws_vpc_endpoint.interface_endpoint[each.value.interface].id
124+
125+
depends_on = [aws_vpc_endpoint_subnet_association.interface]
126+
}

0 commit comments

Comments
 (0)