amazon-web-servicesterraformvpc-endpointaws-route-table

How to retrieve multiple endpoints using data "aws_vpc_endpoint" resource?


Error: “multiple VPC Endpoints matched”

I am using a data “aws_vpc_endpoint” to retrieve multiple endpoint IDs based on the vpc ID. How can I retrieve these endpoints to reference them in another resource? Or is it possible to retrieve multiple endpoint from this data resource. Any suggestions? Or advice would be much appreciated. Here is the code snippet. The count.index has been accounted for correctly already in resource "aws_route" now I am focused on retrieving multiple endpoints to add to the aws_route.

data "aws_vpc_endpoint" "firewall-endpoints" { 
  vpc_id = aws_vpc.vpc.id

  filter {
    name = "tag:Example"
    values = [true]
  }
}

resource "aws_route" "example" {
  count                  = var.number_azs
  route_table_id         = aws_route_table.example[count.index].id
  destination_cidr_block = var.tgw_aws_route[0]
  vpc_endpoint_id = data.aws_vpc_endpoint_service.firewall-endpoints.id
}

Solution

  • The documentation is pretty explicit:

    The arguments of this data source act as filters for querying the available VPC endpoints. The given filters must match exactly one VPC endpoint whose data will be exported as attributes.

    If you want to use VPC endpoints for multiple services, you'll need to create a data source for each one. This could be done concisely with for_each.


    Update: I'm not sure how your endpoints are set up, but you need to find a unique way to refer to them. An example of using for_each here could look like this:

    
    data "aws_region" "current" {}
    
    locals {
      services = {
        s3  = "com.amazonaws.${data.aws_region.current.name}.s3"
        ssm = "com.amazonaws.${data.aws_region.current.name}.ssm"
      }
    }
    
    data "aws_vpc_endpoint" "services" {
      for_each = local.services
    
      vpc_id = aws_vpc.vpc.id
      service_name = each.value
    }
    

    To then use the endpoint, you can refer to it as e.g. data.aws_vpc_endpoint.services["s3"].id. And if you want to loop over them, you can again refer to the local.services dictionary.