Skip to content

Instantly share code, notes, and snippets.

@farshidtz
Last active March 19, 2021 15:02
Show Gist options
  • Save farshidtz/b14f68348c9d5c6a62760fa082a390f3 to your computer and use it in GitHub Desktop.
Save farshidtz/b14f68348c9d5c6a62760fa082a390f3 to your computer and use it in GitHub Desktop.
Three ways to define AWS VPC routing table and association with subnet and internet gateway using Terraform.
# Create a VPC, It comes with a default (automatically created route table)
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/24"
enable_dns_support = true
enable_dns_hostnames = true
enable_classiclink = false
instance_tenancy = "default"
tags = {
Name = "Example"
}
}
# Create a subnet
resource "aws_subnet" "main" {
vpc_id = aws_vpc.main.id
cidr_block = "10.0.0.0/24"
tags = {
Name = "Example"
}
}
# Create Internet Gateway
resource "aws_internet_gateway" "main" {
vpc_id = aws_vpc.main.id
tags = {
Name = "Example"
}
}
## This option leaves behind the default route table created automatically by AWS
## and creates a new one managed by Terraform.
## As a result, there will be two route tables for the VPC, one unused.
# Add an additional route table with route to internet gateway
resource "aws_route_table" "new_route_table" {
vpc_id = aws_vpc.main.id
route {
cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.main.id
}
tags = {
Name = "Example"
}
}
# Associate the subnet with the new route table
resource "aws_route_table_association" "main" {
subnet_id = aws_subnet.main.id
route_table_id = aws_route_table.new_route_table.id
}
# Take ownership of the default (automatically created) route table
# and add internet gateway route and name tag
resource "aws_default_route_table" "default_route_table" {
default_route_table_id = aws_vpc.main.default_route_table_id
route {
cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.main.id
}
tags = {
Name = "Example"
}
}
# Associate the subnet with the route table
resource "aws_route_table_association" "main" {
subnet_id = aws_subnet.main.id
route_table_id = aws_route_table.default_route_table.id
}
## Work with the default route table.
## This is the cleanest option, but it gives no way of naming the default route table
# Add internet gateway route to the default VPC route table
resource "aws_route" "main" {
route_table_id = aws_vpc.main.default_route_table_id
destination_cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.main.id
}
# Associate the default VPC route table to the subnet
resource "aws_route_table_association" "main" {
subnet_id = aws_subnet.main.id
route_table_id = aws_vpc.main.default_route_table_id
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment