I can associate single route table to the AWS VPC Endpoint for S3. But not able to associate multiple route tables with AWS VPC Endpoint for S3.
**Getting below error :
STDERR: \\nError: Invalid index\\n\\n on aws_vpc_endpoints/locals.tf line 30, in locals:\\n 30: route_table_name = rtb[idx]} ] if endp.service_name == \\"s3\\" ]])\\n\\nThis value does not have any indices.\\n"}**
Terraform code :
variable "vpc_endpoints" {
type = list(object({
vpc_name = string
vpc_cidr = list(string)
service = list(object({
service_name = string
subnet_names = optional(list(string))
route_table_names = optional (list(string))
}))
}))
}
Values of Variables :
VPC_Endpoints = [
{
vpc_name = TEST-VPC
vpc_cidr = ["X.X.X.X/X"]
service = [
service_name = s3,
route_table_names = ["Subnet1A", "Subnet1B"]
subnet_names = []
] } ]
We are trying to get list of VPC Name, Subnet Name, Route Tables Names, Tags Name into a map using below locals endp_list and rtb_list.
data "aws_route_tables" "s3_list" {
for_each = { for endp in local.rtb_list : "${endp.vpc_name}-${endp.service_name}" => endp if endp.service_name == "s3"}
filter {
name = "tag:Name"
values = [each.value.route_table_name]
}
}
locals{
endp_list = flatten([ for vpc in var.vpc_endpoints : [ for endp in vpc.service:
{ vpc_name = vpc.vpc_name, service_name = endp.service_name,
subnet_names = endp.subnet_names,
route_table_names = endp.route_table_names,
}]])
rtb_list = flatten([ for vpc in var.vpc_endpoints :
[ for endp in vpc.service:
[ for idx, rtb in endp.route_table_names:
{ vpc_name = vpc.vpc_name,
service_name = endp.service_name,
route_table_name = rtb[idx]} ] if endp.service_name == "s3" ]])
}
resource "aws_vpc_endpoint" "s3" {
for_each = { for endp in local.endp_list : "${endp.vpc_name}-${endp.service_name}" => endp if endp.service_name == "s3" }
vpc_id = data.aws_vpc.vpc[each.value.vpc_name].id
service_name = data.aws_vpc_endpoint_service.s3.service_name
}
resource "aws_vpc_endpoint_route_table_association" "s3_endpoint1_private" {
for_each = { for idx, endp in local.rtb_list : idx => endp if endp.service_name == "s3" }
vpc_endpoint_id = aws_vpc_endpoint.s3["${each.value.vpc_name}-${each.value.service_name}"].id
route_table_id = data.aws_route_table.s3_list[idx].id
}