WireGuard VPN server on EC2 to reach private subnets
A small EC2 instance that lets your team reach databases and internal services in private subnets from a laptop, with one UDP port open and no SSH port at all.
Laptop
WireGuard tunnel
VPN server
Private subnet
How it works
The problem with reaching private resources
Once your database sits in a private subnet, you cannot connect to it from your laptop. The usual shortcuts are to give the database a public address or to open SSH on a server to the internet, and both put a login prompt in front of anyone who scans for one. A VPN gives each person an encrypted path into the VPC and leaves everything else closed.
Launch the server in a public subnet
The instance gets an Elastic IP so its address stays the same, an encrypted disk, and a security group whose only inbound rule is the WireGuard UDP port. WireGuard stays silent unless a packet is signed by a key it knows. For a shell on the server you use Systems Manager Session Manager, so there is no SSH port and no SSH key to manage.
Let the server create its own key
On first boot the server installs WireGuard and generates its key pair on its own disk, readable by root only. The mistake people make is generating the key on a laptop and pasting it into the configuration or user data, where it ends up in the state file and in version control. Here the private key never leaves the instance.
Add a person
Each person generates their own key pair in the WireGuard app and sends you only the public key. Open a Session Manager shell, add a [Peer] block to /etc/wireguard/wg0.conf with that public key and an unused address from the tunnel range, then restart wg-quick@wg0. When someone leaves, delete their block and restart.
Set up the client
In the client configuration, set Endpoint to the endpoint output, PublicKey to the contents of /etc/wireguard/server.pub, and AllowedIPs to the VPC range in the client_allowed_ips output. With that AllowedIPs value only traffic for the VPC goes through the tunnel, and the rest of the person's browsing does not.
Allow the VPN server where it needs to reach
Traffic from VPN users arrives at your databases and services from the VPN server's private address. Add an inbound rule on each target's security group that allows the VPN server's security group on the port needed. Outbound, the server can reach the VPC and HTTPS anywhere, which it needs to install packages and to talk to Session Manager. If your VPC has private endpoints for Systems Manager and for the package repository, set egress_cidrs to the VPC range and the server sends nothing to the internet. Keep the server patched with dnf upgrade: replacing the instance creates a new server key, and every client would need the new one.
What you set
vpc_id
The VPC whose private subnets you want to reach For example vpc-0123456789abcdef0
public_subnet_id
A public subnet in that VPC for the server For example subnet-0123456789abcdef0
vpn_cidr
Address range for the tunnel, not overlapping the VPC or your home and office networks For example 10.99.0.0/24
region
Region the VPC is in For example us-east-1
egress_cidrs
Where the server may send HTTPS, narrow to the VPC range only if it has private endpoints for Systems Manager and packages For example ["0.0.0.0/0"]
What it costs to run
About 10 to 15 dollars a month: one t4g.micro instance, its public IPv4 address and a small disk, plus data transfer for what you send through the tunnel. Estimate.
The configuration
# A small WireGuard VPN server on EC2, for reaching private subnets from a laptop.
#
# What this creates:
# - a security group that accepts only the WireGuard UDP port
# - an EC2 instance in a public subnet, with an encrypted disk and IMDSv2 required
# - an Elastic IP so the server's address never changes
# - an IAM role that lets you open a shell with Systems Manager Session Manager
# (there is no SSH port)
#
# The server's private key is generated on the instance at first boot. It is
# never in this configuration, the state file or the user data.
terraform {
required_version = ">= 1.6.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = var.region
}
variable "region" {
description = "AWS region to deploy into."
type = string
default = "us-east-1"
}
variable "name" {
description = "Short name used for the instance, security group and role."
type = string
default = "wireguard"
}
variable "vpc_id" {
description = "ID of the VPC whose private subnets you want to reach."
type = string
}
variable "public_subnet_id" {
description = "ID of a public subnet in that VPC. The server needs a route to an internet gateway."
type = string
}
variable "instance_type" {
description = "Instance type. Must be an Arm (Graviton) type to match the image. A t4g.micro handles a small team."
type = string
default = "t4g.micro"
}
variable "wireguard_port" {
description = "UDP port WireGuard listens on."
type = number
default = 51820
}
variable "vpn_cidr" {
description = "Address range for the VPN tunnel itself. Must not overlap the VPC or your home and office networks."
type = string
default = "10.99.0.0/24"
}
variable "client_source_cidrs" {
description = "Addresses allowed to send packets to the WireGuard port. Narrow this if everyone connects from fixed addresses."
type = list(string)
default = ["0.0.0.0/0"]
}
variable "egress_cidrs" {
description = "Where the server may send HTTPS, for package updates and Session Manager. Narrow this only if the VPC has private endpoints for both."
type = list(string)
default = ["0.0.0.0/0"]
}
data "aws_vpc" "this" {
id = var.vpc_id
}
# Latest Amazon Linux 2023 image for Arm, looked up from the public parameter
# AWS maintains, so no image ID is hardcoded.
data "aws_ssm_parameter" "al2023" {
name = "/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-arm64"
}
locals {
# The server takes the first address in the tunnel range, for example
# 10.99.0.1/24.
server_address = "${cidrhost(var.vpn_cidr, 1)}/${split("/", var.vpn_cidr)[1]}"
}
resource "aws_security_group" "vpn" {
name = "${var.name}-vpn"
description = "WireGuard VPN server"
vpc_id = var.vpc_id
tags = {
Name = "${var.name}-vpn"
}
}
# The only inbound rule. It is open to the internet by default because people
# connect from home and mobile networks whose addresses change. WireGuard does
# not reply to packets that are not signed by a known client key, so the port
# does not show up in a scan.
resource "aws_vpc_security_group_ingress_rule" "wireguard" {
for_each = toset(var.client_source_cidrs)
security_group_id = aws_security_group.vpn.id
description = "WireGuard"
ip_protocol = "udp"
from_port = var.wireguard_port
to_port = var.wireguard_port
cidr_ipv4 = each.value
}
# Outbound: anything inside the VPC (this is the traffic the VPN carries), and
# HTTPS to the internet for package updates and Session Manager.
resource "aws_vpc_security_group_egress_rule" "vpc" {
security_group_id = aws_security_group.vpn.id
description = "VPN traffic to the VPC"
ip_protocol = "-1"
cidr_ipv4 = data.aws_vpc.this.cidr_block
}
# trivy:ignore:AVD-AWS-0104 The server installs packages and reaches Session Manager over HTTPS at public addresses that change, so port 443 is open by default and egress_cidrs narrows it.
resource "aws_vpc_security_group_egress_rule" "https" {
for_each = toset(var.egress_cidrs)
security_group_id = aws_security_group.vpn.id
description = "Package updates and Session Manager"
ip_protocol = "tcp"
from_port = 443
to_port = 443
cidr_ipv4 = each.value
}
data "aws_iam_policy_document" "assume" {
statement {
effect = "Allow"
actions = ["sts:AssumeRole"]
principals {
type = "Service"
identifiers = ["ec2.amazonaws.com"]
}
}
}
resource "aws_iam_role" "vpn" {
name = "${var.name}-vpn"
assume_role_policy = data.aws_iam_policy_document.assume.json
}
# Session Manager gives you a shell on the server without an SSH port or an
# SSH key to look after. This is the only permission the server has.
resource "aws_iam_role_policy_attachment" "ssm" {
role = aws_iam_role.vpn.name
policy_arn = "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore"
}
resource "aws_iam_instance_profile" "vpn" {
name = "${var.name}-vpn"
role = aws_iam_role.vpn.name
}
resource "aws_instance" "vpn" {
ami = data.aws_ssm_parameter.al2023.value
instance_type = var.instance_type
subnet_id = var.public_subnet_id
vpc_security_group_ids = [aws_security_group.vpn.id]
iam_instance_profile = aws_iam_instance_profile.vpn.name
# A temporary public address so the first boot can download packages before
# the Elastic IP is attached.
associate_public_ip_address = true
# The server key and the client list live on this disk. Termination
# protection stops a stray console click or `tofu destroy` from deleting
# them. To tear down a test, set this to false, apply, then destroy.
disable_api_termination = true
metadata_options {
http_endpoint = "enabled"
http_tokens = "required"
http_put_response_hop_limit = 1
}
root_block_device {
volume_type = "gp3"
volume_size = 8
encrypted = true
}
# Runs once, at first boot. Contains no keys: the server generates its own.
user_data = <<-EOT
#!/bin/bash
set -euo pipefail
for attempt in 1 2 3 4 5 6; do
dnf install -y wireguard-tools iptables-nft && break
sleep 10
done
# Let the server pass packets from VPN clients on to the VPC.
echo "net.ipv4.ip_forward = 1" > /etc/sysctl.d/99-wireguard.conf
sysctl --system
# New files are readable by root only.
umask 077
mkdir -p /etc/wireguard
# Generate the server key pair here, on the instance, and only once.
if [ ! -f /etc/wireguard/server.key ]; then
wg genkey > /etc/wireguard/server.key
wg pubkey < /etc/wireguard/server.key > /etc/wireguard/server.pub
fi
# The private key is loaded from its file when the interface starts, so it
# is not repeated in wg0.conf. Client traffic is rewritten to come from the
# server's own VPC address, so no VPC route table needs to change.
if [ ! -f /etc/wireguard/wg0.conf ]; then
cat > /etc/wireguard/wg0.conf <<'CONF'
[Interface]
Address = ${local.server_address}
ListenPort = ${var.wireguard_port}
PostUp = wg set %i private-key /etc/wireguard/server.key
PostUp = iptables -t nat -A POSTROUTING -s ${var.vpn_cidr} -o $(ip -o -4 route show to default | awk '{print $5; exit}') -j MASQUERADE
PostDown = iptables -t nat -D POSTROUTING -s ${var.vpn_cidr} -o $(ip -o -4 route show to default | awk '{print $5; exit}') -j MASQUERADE
# Add one [Peer] block per person below, then run:
# systemctl restart wg-quick@wg0
#
# [Peer]
# PublicKey = <the client's public key>
# AllowedIPs = <one unused address in the tunnel range>/32
CONF
fi
systemctl enable --now wg-quick@wg0
EOT
tags = {
Name = "${var.name}-vpn"
}
lifecycle {
# A newer image or an edit to the script above would otherwise replace the
# instance, and with it the server key every client is configured with.
# Patch the server in place with `dnf upgrade` instead.
ignore_changes = [ami, user_data]
}
}
# A fixed address, so client configurations keep working after a stop and start.
resource "aws_eip" "vpn" {
domain = "vpc"
instance = aws_instance.vpn.id
tags = {
Name = "${var.name}-vpn"
}
}
output "endpoint" {
description = "Put this in each client's configuration as Endpoint."
value = "${aws_eip.vpn.public_ip}:${var.wireguard_port}"
}
output "instance_id" {
description = "Use this to open a shell: aws ssm start-session --target <instance_id>"
value = aws_instance.vpn.id
}
output "client_allowed_ips" {
description = "Put this in each client's configuration as AllowedIPs, so only traffic for the VPC goes through the tunnel."
value = data.aws_vpc.this.cidr_block
}
output "server_public_key_command" {
description = "Run this in a Session Manager shell to read the server's public key for client configurations."
value = "sudo cat /etc/wireguard/server.pub"
}
Works with OpenTofu 1.6 or later, and with Terraform. Read it before you apply it: it creates real resources in your account.