# =============================================================================
# NAT Gateway infrastructure for existing Control Tower VPC
# Creates: IGW, 1 public subnet, public route table, NAT Gateway
# Adds NAT route to existing private subnet route tables
# =============================================================================
# Data source to read existing VPC details
data "aws_vpc" "existing" {
id = var.vpc_id
}
# Internet Gateway (new — Control Tower VPC has none)
resource "aws_internet_gateway" "main" {
vpc_id = var.vpc_id
tags = merge(
var.tags,
{
Name = "${var.project_name}-${var.environment}-igw"
}
)
}
# Public Subnet for NAT Gateway (small /24 from unused space)
resource "aws_subnet" "public_nat" {
vpc_id = var.vpc_id
cidr_block = var.public_subnet_cidr
availability_zone = var.public_subnet_az
map_public_ip_on_launch = true
tags = merge(
var.tags,
{
Name = "${var.project_name}-${var.environment}-public-nat"
Type = "public"
}
)
}
# Public Route Table
resource "aws_route_table" "public" {
vpc_id = var.vpc_id
route {
cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.main.id
}
tags = merge(
var.tags,
{
Name = "${var.project_name}-${var.environment}-public-rt"
}
)
}
# Associate public subnet with public route table
resource "aws_route_table_association" "public_nat" {
subnet_id = aws_subnet.public_nat.id
route_table_id = aws_route_table.public.id
}
# Elastic IP for NAT Gateway
resource "aws_eip" "nat" {
domain = "vpc"
tags = merge(
var.tags,
{
Name = "${var.project_name}-${var.environment}-nat-eip"
}
)
depends_on = [aws_internet_gateway.main]
}
# NAT Gateway in the public subnet
resource "aws_nat_gateway" "main" {
allocation_id = aws_eip.nat.id
subnet_id = aws_subnet.public_nat.id
tags = merge(
var.tags,
{
Name = "${var.project_name}-${var.environment}-nat"
}
)
depends_on = [aws_internet_gateway.main]
}
# Add NAT Gateway route to existing private subnet route tables
resource "aws_route" "private_nat" {
count = length(var.private_route_table_ids)
route_table_id = var.private_route_table_ids[count.index]
destination_cidr_block = "0.0.0.0/0"
nat_gateway_id = aws_nat_gateway.main.id
}