Sometimes instead of a simple AWS VPC Endpoint, you need to control your own DNS through a Private Hosted Zone (PHZ). This is useful when you have multiple VPCs that need to use the same VPC Endpoints as you cannot share the AWS created DNS across VPCs/Accounts. In this guide, we’ll walk through how to set up a VPC Endpoint with a Private Hosted Zone using Terraform.
Challenge
AWS VPC Endpoint DNS is typically limited to the originating VPC. This means that if you have multiple VPCs that need to access the same VPC Endpoint, you can’t share the DNS resolution across VPCs. This is a problem if you have a multi-account or multi-VPC setup where you want to share a VPC Endpoint across VPCs.
When you create a VPC Endpoint, and turn off the private_dns_enabled
flag, you lose the ability to use the AWS provided DNS. You also are not given information about what DNS records you should have created in your Private Hosted Zone. Making assumptions here leads to a lot of misses and misconfigurations. Fortunately, the data is available in the AWS API, and we can use Terraform to extract it.
Solution
Using aws_vpc_endpoint_service
to create a dynamic configuration that handles all the multitude of DNS entries is a solution where we remove the guess work from this process. This is a relatively new ability, as the data object for this resource was missing the required private_dns_names
until recently (Yes, that’s my commit, you’re welcome). Let’s break it down step by step.
1. Define Your VPCes
First, define which VPC Endpoint Services you want to create:
|
|
2. Lookup and Create VPC Endpoints
Look up the details of each VPC desired endpoint and create the VPC Endpoint:
|
|
3. Some convoluted terraform processing and loops
Here’s where the magic happens. We’ll use nested for_each
operations to create all possible dns entries and needed metadata for creating zones and records:
|
|
4. Create the Private Hosted Zones for the VPC Endpoints
Here we will create our PHZ, this way we can selectively share the DNS entries across VPCs:
|
|
Results
When you apply this configuration, you’ll see outputs confirming that terraform has successfully created VPC endpoints and PHZs for each service
Example output:
|
|
Complete example
I know in the end, we all just want a complete example to copy-paste. Here you go:
|
|