AWS VPC Configuration

Written
  • AWS sets up a bunch of convenient things in the default VPC for an account, which you may need to recreate when making a new VPC. Here's how to do that in Terraform.
  • First, the VPC and subnets:
    • resource "aws_vpc" "my_app" {
        cidr_block = var.my_app_cidr
        tags = {
          Name = "my_app"
        }
      }
      
      resource "aws_subnet" "my_app" {
        vpc_id = aws_vpc.my_app.id
        cidr_block = var.my_app_cidr
        # Set appropriately for your needs
        map_public_ip_on_launch = true
        availability_zone = var.az
        tags = {
          Name = "my_app"
        }
      }
      
      
  • For tasks that access the internet, you also need an internet gateway and a routing table to use it.
    • You can also use a NAT gateway or something, but this is the simplest and cheapest way to go.
    • Here we'll also set up a VPC endpoint to link directly into S3, which saves egress charges for going through public routes.
    • resource "aws_internet_gateway" "my_app" {
        vpc_id = aws_vpc.my_app.id
      
        tags = {
          Name = "my_app"
        }
      }
      
      resource "aws_route_table" "my_app" {
        vpc_id = aws_vpc.my_app.id
      
        route {
          cidr_block = "0.0.0.0/0"
          gateway_id = aws_internet_gateway.my_app.id
        }
      
        tags = {
          Name = "my_app"
        }
      }
      
  • Finally, we set up a VPC endpoint to communicate directly with S3, without needing to go through the public internet. This can improve performance and save money.
    • resource "aws_vpc_endpoint" "my_app_s3" {
        vpc_id       = aws_vpc.my_app.id
        service_name = "com.amazonaws.us-west-2.s3"
      
        tags = {
          Name = "my_app_s3"
        }
      }
      
      resource "aws_vpc_endpoint_route_table_association" "my_app_s3" {
        vpc_endpoint_id = aws_vpc_endpoint.my_app_s3.id
        route_table_id = aws_route_table.my_app.id
      }
      
      

Thanks for reading! If you have any questions or comments, please send me a note on Twitter.