Reputation: 1733
I've created multiple subnets and multiple VPC endpoints using the for_each
loop as follows:
### VARIABLES ###
variable "private_cidr_mask" {
default = {
"us-west-1a" = "10.0.1.0/24"
"us-west-1b" = "10.0.2.0/24"
}
}
variable "vpc_endpoints" {
default = [
"com.amazonaws.us-west-1.ecs-agent",
"com.amazonaws.us-west-1.ecs-telemetry",
"com.amazonaws.us-west-1.ecs"
]
}
### RESOURCES ###
resource "aws_subnet" "private_subnet" {
for_each = var.private_cidr_mask
vpc_id = aws_vpc.vpc.id
availability_zone = each.key
cidr_block = each.value
}
resource "aws_vpc_endpoint" "vpc_endpoint" {
for_each = toset(var.vpc_endpoints)
vpc_id = aws_vpc.vpc.id
vpc_endpoint_type = "Interface"
service_name = each.value
security_group_ids = [ aws_security_group.security_group.id ]
private_dns_enabled = true
}
Now I have to assign every VPC endpoint to each of the private subnets using a aws_vpc_endpoint_subnet_association
:
resource "aws_vpc_endpoint_subnet_association" "vpc_endpoint_subnet_association" {
vpc_endpoint_id = <every endpoint>
subnet_id = <every subnet>
}
How do I achieve this in Terraform? I have tried nested for_each loops without success.
Upvotes: 6
Views: 22375
Reputation: 1733
It turns out that aws_vpc_endpoint
accepts a list of subnet_ids
and I just missed it in the docs, so all I had to do was:
resource "aws_vpc_endpoint" "vpc_endpoint" {
for_each = toset(var.vpc_endpoints)
vpc_id = aws_vpc.vpc.id
vpc_endpoint_type = "Interface"
service_name = each.value
security_group_ids = [ aws_security_group.security_group.id ]
subnet_ids = [ for subnet in aws_subnet.private_subnet: subnet.id ]
private_dns_enabled = true
}
Upvotes: 3
Reputation: 1267
Within the aws_vpc_endpoint_subnet_association resource creation
Have you thought about using the count command based upon Looking up the number of vpc_endpoints?
You could then have a single for each of the subnet id within it.
Upvotes: 0