Terraform multiple for_each resources
10,990
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
}
Author by
smilin_stan
Updated on June 14, 2022Comments
-
smilin_stan almost 2 years
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.
-
Martin Atkins over 4 yearsThe example at terraform.io/docs/configuration/functions/… might give some useful pointers
-