VPN Server on AWS with Terraform + WireGuard
A complete, from-scratch walkthrough: infrastructure as code, VPN protocol fundamentals, and automation — built the way a production VPN would be built at a company.
Building a Self-Hosted VPN Server on AWS with Terraform and WireGuard
A complete DevOps tutorial: infrastructure as code, VPN protocol fundamentals, and automation.
Table of contents
01What You’re Building and Why
By the end of this guide you will have:
- A WireGuard VPN server running on an AWS EC2 instance
- Fully provisioned through Terraform — no manual console clicking, no manual SSH configuration
- A script that generates new client configs (and QR codes) in one command
- Security hardening by default: no open SSH port, minimal open ports, secrets kept out of state files
- Access to the server handled entirely through AWS SSM, not SSH keys
This is deliberately built the way a production VPN would be built at a company, not the way a “install OpenVPN on Ubuntu” blog post does it. The difference matters: a tutorial that just runs apt install openvpn teaches you a command. This guide teaches you the reasoning behind each resource, so you can adapt it, debug it, and explain it in an interview.
02Core Concepts You Need First
If you already know these, skip ahead. If any of these are fuzzy, read this section carefully — everything after it assumes you understand these.
2.1 What a VPN actually does
A VPN (Virtual Private Network) creates an encrypted tunnel between two points — your laptop and a server, in this case. Once the tunnel is up, your device gets a virtual network interface with its own IP address inside that tunnel. Traffic sent to that interface gets encrypted, sent to the VPN server, decrypted, and then routed onward (either to the wider internet, or to other machines on the server’s private network).
Two things a VPN is used for, and this project supports both: - Remote access: securely reach private resources (e.g., a database in a private subnet) without exposing them to the public internet. - Traffic tunneling: route your internet traffic through the server (useful for a fixed egress IP, or bypassing local network restrictions).
2.2 Why WireGuard instead of OpenVPN
| OpenVPN | WireGuard | |
|---|---|---|
| Codebase size | ~70,000 lines | ~4,000 lines |
| Protocol | Configurable, TLS-based | Fixed, modern cryptography only |
| Performance | Slower (userspace, TLS overhead) | Faster (kernel module, minimal handshake) |
| Config complexity | Certificates, CAs, .ovpn files |
Two keys and a few lines of config |
| Automation-friendliness | Harder to script (PKI management) | Easy — key generation is a single command |
WireGuard’s config is small enough that generating a new client is a scripting problem, not a PKI-management problem. That’s why it’s the better choice for an automated, IaC-driven project like this one.
2.3 WireGuard’s actual model: public-key routing, not client/server
This is the part most tutorials skip, and it’s the part that actually matters for understanding your own config files.
WireGuard doesn’t have a traditional “client connects to server” handshake with certificates. Instead:
- Every peer (server or client) has a private key (kept secret) and a public key (derived from it, shared with peers).
- Each peer’s config lists the peers it’s willing to talk to, each identified by their public key.
AllowedIPson each peer entry does double duty: it’s both a routing rule (“send traffic for this IP range through this peer”) and a firewall rule (“only accept traffic claiming to be from this IP range, from this peer”).- There’s no concept of “the server accepts connections.” Every peer just sends encrypted UDP packets to the address:port of a peer it knows about. If a valid handshake happens, an ephemeral session key is derived and traffic flows.
Concretely, that means your VPN server’s config will have an [Interface] section (its own identity) and one [Peer] block per client. Each client’s config will have its own [Interface] section (its identity) and exactly one [Peer] block — the server.
2.4 CIDR blocks, quickly
You’ll see addresses like 10.0.0.0/24 and 10.8.0.0/24 throughout this guide.
/24means the first 24 bits are fixed (the network part), and the remaining 8 bits can vary → 256 addresses.10.0.0.0/24covers10.0.0.0to10.0.0.255./28means the first 28 bits are fixed → 16 addresses. Used here for the public subnet, which only ever needs to hold one EC2 instance./32means every bit is fixed — a single address. Used for “this one exact client.”
You’ll use 10.0.0.0/24 for the AWS VPC and a separate, non-overlapping range, 10.8.0.0/24, for the WireGuard tunnel network. Keeping them separate avoids routing conflicts.
2.5 Terraform concepts used in this guide
A quick primer on the Terraform building blocks this project relies on, so the code in the following sections isn’t a wall of unfamiliar syntax:
- Provider: a plugin that lets Terraform talk to a specific platform’s API — here, the
awsprovider block, authenticated the same way the AWS CLI is (env vars, an AWS CLI profile, or an IAM role). - Module: a reusable, self-contained group of resources with its own inputs (variables) and outputs. This project is split into three modules —
network,security,vpn-instance— instead of one flatmain.tf, so each piece has a single responsibility and can be changed independently. user_data: a shell script that AWS runs automatically, exactly once, the first time an EC2 instance boots. This is where WireGuard actually gets installed and configured — think of it as the equivalent of a container’sENTRYPOINTscript, except it only fires on first boot, not on every restart.- State: Terraform’s record of what it has already created, so future runs know what to change instead of creating everything from scratch. Never commit
terraform.tfstateto version control — it can contain sensitive values. This project uses a remote backend (S3) so the state survives a laptop wipe and can be shared safely if more than one person ever works on it.
03Architecture Overview
Internet
│
│ UDP 51820 (WireGuard)
▼
┌─────────────────────┐
│ Elastic IP │
└──────────┬───────────┘
│
┌─────────────▼─────────────┐
│ Public Subnet (10.0.0.0/28)
│ ┌───────────────────────┐ │
│ │ EC2: WireGuard Server │ │
│ │ wg0: 10.8.0.1/24 │ │
│ └───────────┬───────────┘ │
└──────────────┼─────────────┘
│ encrypted tunnel (10.8.0.0/24)
┌───────────┼────────────┐
▼ ▼ ▼
Client A Client B Client C
10.8.0.2/32 10.8.0.3/32 10.8.0.4/32
VPC CIDR: 10.0.0.0/24 WireGuard tunnel CIDR: 10.8.0.0/24
Key point: the VPC network (10.0.0.0/24, AWS-managed) and the WireGuard tunnel network (10.8.0.0/24, WireGuard-managed) are two completely separate layers. The EC2 instance has a foot in both — a regular ENI on the VPC side, and a wg0 virtual interface on the tunnel side.
Notice there’s no inbound SSH port in this diagram at all. Access to the instance for administration goes through AWS SSM (covered in Section 9), authenticated by IAM rather than an SSH key — so port 22 is never opened in the first place.
04Prerequisites
- An AWS account with programmatic access (access key + secret, or SSO profile)
- Terraform ≥ 1.5 installed (
terraform -version) - AWS CLI installed and configured (
aws sts get-caller-identityshould return your account) wireguard-toolsinstalled locally (for generating client keypairs and testing) —sudo apt install wireguard-toolson Ubuntu/Debian,brew install wireguard-toolson macOS- Basic comfort with SSH and reading shell scripts
05Project Structure
vpn-server-terraform/
├── modules/
│ ├── network/
│ │ ├── main.tf
│ │ ├── variables.tf
│ │ └── outputs.tf
│ ├── security/
│ │ ├── main.tf
│ │ ├── variables.tf
│ │ └── outputs.tf
│ └── vpn-instance/
│ ├── main.tf
│ ├── iam.tf
│ ├── variables.tf
│ ├── outputs.tf
│ └── templates/
│ └── user_data.sh.tpl
├── scripts/
│ ├── add_client.sh
│ └── generate-qr.py
├── environments/
│ └── dev/
│ ├── main.tf
│ ├── variables.tf
│ ├── outputs.tf
│ ├── terraform.tfvars
│ └── backend.tf
└── README.md
Why split into modules instead of one main.tf? Each module has one responsibility — networking, firewall, compute — so it can be reasoned about, changed, and tested on its own. It also means a second environment (say, environments/prod) can reuse the exact same modules by pointing at them with different variables, instead of duplicating resource definitions.
06Step 1 — Networking Layer
File: modules/network/main.tf
resource "aws_vpc" "vpn_vpc" {
cidr_block = var.vpc_cidr
enable_dns_support = true
enable_dns_hostnames = true
tags = {
Name = "${var.project_name}-vpc"
}
}
resource "aws_subnet" "public" {
vpc_id = aws_vpc.vpn_vpc.id
cidr_block = var.public_subnet_cidr
map_public_ip_on_launch = true
availability_zone = var.availability_zone
tags = {
Name = "${var.project_name}-public-subnet"
}
}
resource "aws_internet_gateway" "igw" {
vpc_id = aws_vpc.vpn_vpc.id
tags = {
Name = "${var.project_name}-igw"
}
}
resource "aws_route_table" "public" {
vpc_id = aws_vpc.vpn_vpc.id
route {
cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.igw.id
}
tags = {
Name = "${var.project_name}-public-route-table"
}
}
resource "aws_route_table_association" "public" {
subnet_id = aws_subnet.public.id
route_table_id = aws_route_table.public.id
}
Line-by-line explanation:
aws_vpc: the isolated network your instance lives in.enable_dns_support/enable_dns_hostnamesare turned on so the instance gets a resolvable internal DNS name — not strictly required for a VPN server, but harmless and useful if you add more resources later.aws_subnet.public: a slice of the VPC’s address range tied to one Availability Zone.map_public_ip_on_launch = truemeans any instance launched here automatically gets a public IP — needed because clients out on the internet must be able to reach this box.aws_internet_gateway: the VPC’s door to the internet. Without this, nothing in the VPC can send or receive internet traffic, no matter what security groups say.aws_route_table+route: this is the actual instruction “traffic headed anywhere (0.0.0.0/0) goes out through the internet gateway.” A subnet without a route to an IGW is a private subnet, no matter how its security group is configured — routing and firewalling are two separate layers, and it’s a common beginner mistake to configure only one of them.aws_route_table_association: attaches that routing rule to the specific subnet. Route tables aren’t automatically applied — you must explicitly associate them.
File: modules/network/variables.tf
variable "project_name" {
type = string
}
variable "vpc_cidr" {
type = string
default = "10.0.0.0/24"
}
variable "public_subnet_cidr" {
type = string
default = "10.0.0.0/28"
}
variable "availability_zone" {
type = string
}
The subnet is deliberately small (/28, 16 addresses) — this project only ever puts a single EC2 instance in it, so there’s no reason to reserve a full /24.
File: modules/network/outputs.tf
output "vpc_id" {
value = aws_vpc.vpn_vpc.id
}
output "public_subnet_id" {
value = aws_subnet.public.id
}
Outputs are how this module hands its resource IDs up to whatever calls it — the security and vpn-instance modules need the VPC ID and subnet ID, and this is how they get them without reaching into another module’s internals directly.
07Step 2 — Security Group
File: modules/security/main.tf
resource "aws_security_group" "vpn_sg" {
name = "${var.project_name}-vpn-sg"
vpc_id = var.vpc_id
tags = {
Name = "${var.project_name}-vpn-sg"
}
}
resource "aws_vpc_security_group_ingress_rule" "wireguard" {
description = "Wire Guard"
security_group_id = aws_security_group.vpn_sg.id
ip_protocol = "udp"
from_port = 51820
to_port = 51820
cidr_ipv4 = "0.0.0.0/0"
tags = {
Name = "wireguard"
}
}
resource "aws_vpc_security_group_egress_rule" "allow_all_traffic_ipv4" {
security_group_id = aws_security_group.vpn_sg.id
ip_protocol = "-1"
cidr_ipv4 = "0.0.0.0/0"
tags = {
Name = "allow-outbound-traffic"
}
}
Why each rule exists:
- WireGuard ingress on UDP 51820, open to
0.0.0.0/0: this has to be open to the world, because your clients will connect from wherever they physically are — home Wi-Fi, mobile data, a coffee shop. There’s no way to predict their source IP in advance. This is safe specifically because WireGuard silently drops any packet that doesn’t pass its cryptographic handshake — an open UDP port with no valid key gets no response at all, so it doesn’t even reveal that a WireGuard service is running there (this is called being “invisible to port scans,” and it’s a real security property, not marketing). - No SSH ingress rule at all: port 22 simply isn’t opened. Administrative access instead goes through AWS SSM Session Manager (Section 9), which authenticates via IAM rather than a key pair and needs no inbound port whatsoever. This is a stricter default than “restrict SSH to your IP,” and it’s the default this project ships with rather than an optional hardening step you add later.
- Egress
-1(all protocols) to0.0.0.0/0: outbound is left open because the instance needs to reach the internet for package installs and to relay client traffic onward. Locking down egress is possible but adds complexity disproportionate to what this project needs. aws_vpc_security_group_ingress_rule/_egress_ruleinstead of inlineingress {}/egress {}blocks: these are standalone resources rather than attributes nested insideaws_security_group. The practical benefit is that Terraform can add, remove, or change one rule without having to recreate the whole security group, and each rule shows up as its own resource interraform planoutput — easier to review when you’re checking a diff beforeapply.
File: modules/security/variables.tf
variable "project_name" { type = string }
variable "vpc_id" { type = string }
File: modules/security/outputs.tf
output "security_group_id" {
value = aws_security_group.vpn_sg.id
}
08Step 3 — The VPN Instance
File: modules/vpn-instance/main.tf
resource "aws_eip" "vpn_eip" {
domain = "vpc"
tags = {
Name = "${var.project_name}-vpn-eip"
}
}
resource "aws_instance" "vpn_server" {
ami = var.ami_id
instance_type = var.instance_type
subnet_id = var.subnet_id
vpc_security_group_ids = [var.security_group_id]
key_name = var.key_name
iam_instance_profile = aws_iam_instance_profile.ssm.name
user_data = templatefile("${path.module}/templates/user_data.sh.tpl", {
wg_port = var.wg_port
server_wg_ip = var.server_wg_ip
aws_region = var.aws_region
})
metadata_options {
http_tokens = "required" # enforce IMDSv2 — blocks a whole class of SSRF-based credential theft
}
root_block_device {
volume_size = 20
volume_type = "gp3"
encrypted = true
}
tags = {
Name = "${var.project_name}-vpn-server"
}
}
resource "aws_eip_association" "vpn_eip_association" {
instance_id = aws_instance.vpn_server.id
allocation_id = aws_eip.vpn_eip.id
}
Explanation of the non-obvious bits:
aws_eip(Elastic IP): a static public IP that stays the same across instance replacements. Without this, redeploying the instance would give clients a new server IP every time, breaking every existing client config. This is the single most important reliability detail in the whole setup — skip it and your “VPN server” changes address every time youterraform applya change that replaces the instance.iam_instance_profile = aws_iam_instance_profile.ssm.name: attaches the IAM role defined iniam.tf(next) to the instance. This is what makes SSM Session Manager andaws ssm put-parameterwork from inside the instance without any SSH key or hardcoded credentials — the instance authenticates as itself, via IAM.user_data+templatefile:templatefile()reads a script file and substitutes${...}placeholders with real values — this is how Terraform-level variables (like which UDP port you chose, or which AWS region you’re deploying to) end up inside a shell script that runs on the instance.metadata_options.http_tokens = "required": forces IMDSv2 (the newer, token-based version of the EC2 metadata service). IMDSv1 is a known SSRF (server-side request forgery) vector — if any software running on the box has a bug that lets an attacker make it fetch an arbitrary URL, IMDSv1 lets them steal the instance’s IAM credentials through it. This single line closes that hole. Worth mentioning in an interview — it’s a real, current AWS security best practice, not a toy example.root_block_device.encrypted = true: encrypts the EBS volume at rest. Costs nothing extra, and there’s no good reason not to.aws_eip_association: a separate resource (rather than an inline attribute on the instance) because it lets Terraform manage the EIP’s lifecycle independently — you can detach/reattach without destroying either resource.
File: modules/vpn-instance/iam.tf
data "aws_iam_policy_document" "ssm" {
statement {
actions = ["sts:AssumeRole"]
principals {
type = "Service"
identifiers = ["ec2.amazonaws.com"]
}
}
}
resource "aws_iam_role" "ssm" {
name = "${var.project_name}-ssm-role"
assume_role_policy = data.aws_iam_policy_document.ssm.json
tags = {
Name = "${var.project_name}-ssm-role"
}
}
resource "aws_iam_role_policy_attachment" "ssm" {
role = aws_iam_role.ssm.name
policy_arn = "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore"
}
resource "aws_iam_instance_profile" "ssm" {
name = "${var.project_name}-ssm-instance-profile"
role = aws_iam_role.ssm.name
}
resource "aws_iam_role_policy" "ssm_put_param" {
role = aws_iam_role.ssm.id
name = "${var.project_name}-ssm-put-param-policy"
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Action = ["ssm:PutParameter"]
Effect = "Allow"
Resource = "arn:aws:ssm:*:*:parameter/vpn/server_public_key"
}
]
})
}
Why this exists, and why it’s scoped this tightly:
aws_iam_role+AmazonSSMManagedInstanceCore: this is the AWS-managed policy that lets the SSM Agent (already bundled on modern Ubuntu AMIs) register the instance with SSM, which is what enables both Session Manager (interactive shell, Section 9) and Run Command (used byadd_client.sh, Section 12).aws_iam_role_policy.ssm_put_param: a second, narrow policy that grants exactly one additional permission —ssm:PutParameter, and only on the specific parameter path/vpn/server_public_key. This is what lets the boot script publish the server’s public key (Section 9) without granting the instance broad SSM or IAM permissions it doesn’t need. Scoping theResourcethis tightly instead of using*is the difference between “this instance can publish one specific value” and “this instance can read or write any SSM parameter in the account,” which matters a lot if the instance is ever compromised.
File: modules/vpn-instance/variables.tf
variable "project_name" {
description = "The name of the project"
type = string
}
variable "ami_id" {
description = "The ID of the AMI to use for the VPN instance"
type = string
}
variable "instance_type" {
type = string
default = "t3.micro"
}
variable "subnet_id" {
description = "The ID of the subnet where the VPN instance will be deployed"
type = string
}
variable "security_group_id" {
description = "The ID of the security group to use for the VPN instance"
type = string
}
variable "key_name" {
description = "The name of the key pair to use for the VPN instance"
type = string
}
variable "wg_port" {
description = "The port for WireGuard"
type = number
default = 51820
}
variable "server_wg_ip" {
description = "The WireGuard tunnel IP address assigned to the server"
type = string
default = "10.8.0.1"
}
variable "aws_region" {
description = "The AWS region where the resources will be created"
type = string
}
key_name still refers to an EC2 key pair — Terraform requires one to launch the instance — but because SSH is never opened in the security group, you won’t actually use that key pair to log in. It’s a required launch parameter, not an access path.
File: modules/vpn-instance/outputs.tf
output "public_ip" {
value = aws_eip.vpn_eip.public_ip
}
output "instance_id" {
value = aws_instance.vpn_server.id
}
09Step 4 — WireGuard Bootstrap Script
This is the script that turns a blank EC2 instance into a working WireGuard server, automatically, on first boot.
File: modules/vpn-instance/templates/user_data.sh.tpl
#!/bin/bash
set -euxo pipefail
# --- Install WireGuard ---
apt-get update -y
apt-get install -y wireguard qrencode
apt-get install -y unzip
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
./aws/install
aws --version
# --- Enable IP Forwarding ---
echo "net.ipv4.ip_forward=1" >> /etc/sysctl.conf
sysctl -p
# --- Generate Server Keys ---
mkdir -p /etc/wireguard
wg genkey | tee /etc/wireguard/server_private.key | wg pubkey > /etc/wireguard/server_public.key
chmod 600 /etc/wireguard/server_private.key
SERVER_PRIVATE_KEY=$(cat /etc/wireguard/server_private.key)
# --- Create WireGuard Configuration ---
cat <<EOF > /etc/wireguard/wg0.conf
[Interface]
Address = ${server_wg_ip}/24
ListenPort = ${wg_port}
PrivateKey = $SERVER_PRIVATE_KEY
SaveConfig = true
PostUp = iptables -t nat -A POSTROUTING -s ${server_wg_ip}/24 -j MASQUERADE
PostDown = iptables -t nat -D POSTROUTING -s ${server_wg_ip}/24 -j MASQUERADE
EOF
chmod 600 /etc/wireguard/wg0.conf
# --- Enable and Start WireGuard ---
systemctl enable wg-quick@wg0
systemctl start wg-quick@wg0
# --- Publish server public key for client provisioning ---
aws ssm put-parameter \
--name "/vpn/server_public_key" \
--type String \
--value "$(cat /etc/wireguard/server_public.key)" \
--overwrite \
--region ${aws_region}
Concept-by-concept breakdown:
set -euxo pipefail:-eexits on any command failure (so a broken step doesn’t silently continue),-uerrors on undefined variables,-xprints every command before running it (invaluable for debugging boot scripts viacloud-initlogs),-o pipefailmakes a pipeline fail if any stage of it fails, not just the last one. This combination is close to a standard defensive-bash-script header worth reusing in any provisioning script you write.- Installing the AWS CLI by hand (
curl+unzip+./aws/install): the base Ubuntu 22.04 AMI doesn’t ship the AWS CLI, but this script needs it to publish the server’s public key to SSM Parameter Store. Downloading the official installer bundle at boot keeps the AMI itself generic — nothing AWS-CLI-specific has to be baked into a custom image. - IP forwarding (
net.ipv4.ip_forward=1): this is the single most commonly forgotten step by people following VPN tutorials, and it’s the #1 cause of “I can connect but I have no internet” symptoms. WireGuard establishing a tunnel and Linux actually routing packets through that tunnel are two separate concerns. - Why keys are generated on-instance, not in Terraform: if you generated the private key in Terraform and it ended up in a resource, it would be stored in the Terraform state file — and state files are famously not secrets-safe (they’re often stored in S3, sometimes committed by mistake, and readable by anyone with
terraform state showaccess). Generating keys insideuser_datameans the private key exists only on the box that needs it. SaveConfig = true: tells WireGuard to write back the running configuration (including any peers added live withwg set) towg0.confon shutdown, so peers added dynamically via theadd_client.shscript (next section) survive a reboot.iptables ... MASQUERADE, scoped with-s ${server_wg_ip}/24: this is standard NAT (Network Address Translation). Client traffic arrives at the server with a source IP in the10.8.0.0/24tunnel range — the wider internet has no idea how to route a reply back to10.8.0.2. MASQUERADE rewrites the source IP to the server’s own public-facing IP before the packet leaves, so replies come back to the server, which WireGuard then knows how to route back into the tunnel to the right client. Matching on-s ${server_wg_ip}/24(the tunnel subnet) rather than a specific outbound interface name means the rule only rewrites traffic that actually originated from a WireGuard peer, not every packet leaving the box.- The SSM Parameter Store block: rather than you having to connect to the box just to read the server’s public key (which you need to build every client config), the boot script publishes it to a location your local
add_client.shscript can read via the AWS CLI. Because the instance already has the IAM role fromiam.tf,aws ssm put-parameterworks with no separate credentials — it just needs--regionsince the CLI has no other way to infer it non-interactively.
10Step 5 — Wiring the Modules Together
File: environments/dev/main.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "6.56.0"
}
}
}
provider "aws" {
region = var.aws_region
}
data "aws_ami" "ubuntu" {
most_recent = true
owners = ["099720109477"] # Canonical
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*"]
}
filter {
name = "virtualization-type"
values = ["hvm"]
}
}
module "network" {
source = "../../modules/network"
project_name = var.project_name
availability_zone = var.availability_zone
}
module "security" {
source = "../../modules/security"
project_name = var.project_name
vpc_id = module.network.vpc_id
}
module "vpn_instance" {
source = "../../modules/vpn-instance"
project_name = var.project_name
ami_id = coalesce(var.ami_id, data.aws_ami.ubuntu.id)
instance_type = var.instance_type
subnet_id = module.network.public_subnet_id
security_group_id = module.security.security_group_id
key_name = var.ssh_key_name
wg_port = var.wg_port
server_wg_ip = var.server_wg_ip
aws_region = var.aws_region
}
This file is deliberately thin — it doesn’t define infrastructure of its own beyond the AMI lookup, only wires the three modules together by passing outputs from one (module.network.vpc_id) as inputs to another.
data "aws_ami" "ubuntu" is worth calling out: instead of hardcoding an AMI ID (which is region-specific and goes stale as Canonical publishes new images), this data source asks AWS for the most recent Ubuntu 22.04 LTS AMI at plan time, filtered to Canonical’s own account (099720109477) so you’re not trusting a random public AMI. coalesce(var.ami_id, data.aws_ami.ubuntu.id) means: use var.ami_id if you’ve explicitly set one, otherwise fall back to whatever the data source found — so you can pin a specific AMI later without changing any code.
File: environments/dev/variables.tf
variable "project_name" {
type = string
}
variable "aws_region" {
type = string
}
variable "availability_zone" {
type = string
}
variable "ami_id" {
description = "AMI ID override; if left null, the latest Ubuntu 22.04 LTS AMI for the region is used"
type = string
default = null
}
variable "instance_type" {
type = string
default = "t3.micro"
}
variable "ssh_key_name" {
type = string
}
variable "wg_port" {
type = number
default = 51820
}
variable "server_wg_ip" {
type = string
default = "10.8.0.1"
}
File: environments/dev/terraform.tfvars
project_name = "personal-vpn"
aws_region = "eu-west-1"
availability_zone = "eu-west-1a"
ssh_key_name = "your-ec2-keypair-name"
There’s no ami_id here — leaving it unset means Terraform resolves the latest Ubuntu AMI automatically via the data "aws_ami" lookup above. Set it explicitly only if you want to pin to a specific image.
File: environments/dev/backend.tf
terraform {
backend "s3" {
bucket = "your-terraform-state-bucket"
key = "vpn-server/dev/terraform.tfstate"
region = "eu-west-1"
encrypt = true
}
}
Using a remote backend (rather than a local .tfstate file) matters even for a solo project: it means your state survives a laptop wipe, and encrypt = true ensures the state — which can contain sensitive values — is encrypted at rest in S3. Modern versions of the S3 backend support native state locking without a separate DynamoDB table, which is why you won’t see one here.
File: environments/dev/outputs.tf
output "vpc_id" {
value = module.network.vpc_id
}
output "public_subnet_id" {
value = module.network.public_subnet_id
}
output "security_group_id" {
value = module.security.security_group_id
}
output "vpn_public_ip" {
value = module.vpn_instance.public_ip
}
output "vpn_instance_id" {
value = module.vpn_instance.instance_id
}
The two you’ll actually use day to day are vpn_public_ip and vpn_instance_id — the rest exist mostly for debugging and for chaining into other tooling later.
11Step 6 — Deploying
cd environments/dev
terraform init # downloads providers, configures the S3 backend
terraform plan # shows exactly what will be created — read this before applying
terraform apply # provisions everything; type 'yes' to confirm
terraform init needs to be re-run any time you add a new provider or change the backend config. terraform plan is not optional to skip — it’s your only chance to catch a typo’d CIDR block or an accidentally-open security group rule before it becomes a real, billable, internet-facing resource.
After apply finishes:
terraform output vpn_public_ip
That’s your VPN server’s address. Give it 30–60 seconds after the instance reaches “running” state for user_data to finish executing before trying to connect a client.
12Step 7 — Adding Client Devices
File: scripts/add_client.sh
#!/bin/bash
set -euo pipefail
CLIENT_NAME=$1
SERVER_IP=$(terraform -chdir=environments/dev output -raw vpn_public_ip)
SERVER_PUBLIC_KEY=$(aws ssm get-parameter --name "/vpn/server_public_key" --query "Parameter.Value" --output text)
WG_SUBNET_PREFIX="10.8.0"
# Assign the next free IP in the tunnel range. In a real multi-client setup
# you'd track this in SSM or a small database; for a personal project,
# incrementing based on a locally kept counter file is enough.
CLIENT_NUM=$(cat .client_counter 2>/dev/null || echo 1)
CLIENT_IP="${WG_SUBNET_PREFIX}.$((CLIENT_NUM + 1))"
echo $((CLIENT_NUM + 1)) > .client_counter
# Generate the client's own keypair, locally — the private key never
# touches the server.
CLIENT_PRIVATE_KEY=$(wg genkey)
CLIENT_PUBLIC_KEY=$(echo "$CLIENT_PRIVATE_KEY" | wg pubkey)
# Write the client config file
cat > "${CLIENT_NAME}.conf" <<EOF
[Interface]
PrivateKey = $CLIENT_PRIVATE_KEY
Address = ${CLIENT_IP}/32
DNS = 1.1.1.1
[Peer]
PublicKey = $SERVER_PUBLIC_KEY
Endpoint = ${SERVER_IP}:51820
AllowedIPs = 0.0.0.0/0
PersistentKeepalive = 25
EOF
echo "Registering peer on the server via SSM Run Command..."
INSTANCE_ID=$(terraform -chdir=environments/dev output -raw vpn_instance_id)
aws ssm send-command \
--instance-ids "$INSTANCE_ID" \
--document-name "AWS-RunShellScript" \
--parameters commands="wg set wg0 peer $CLIENT_PUBLIC_KEY allowed-ips ${CLIENT_IP}/32"
echo "Client config written to ${CLIENT_NAME}.conf"
What’s happening here, and why:
- The client’s private key is generated locally, never on the server. This is a core WireGuard security principle: each party generates its own keypair and only ever shares its public key with the others. If the server generated client keys, the server would have (at least briefly) held every client’s private key — a much bigger blast radius if the server were ever compromised.
AllowedIPs = 0.0.0.0/0in the client config: this tells the client “route ALL my internet traffic through the tunnel” — this is what makes it a full VPN (as opposed to split tunneling, where you’d list only specific subnets like10.0.0.0/24to route just internal traffic through the tunnel while everything else goes out your normal connection).PersistentKeepalive = 25: WireGuard is built on UDP, which is connectionless — there’s no persistent “session” the way TCP has one. Most NAT devices (home routers, mobile carrier NAT) silently drop a UDP mapping if no traffic passes for a while, which would make the server unable to reach the client until the client sends something first. Sending a tiny keepalive packet every 25 seconds keeps that NAT mapping alive. This line is optional on a server-side config but essential on a client that’s behind NAT (almost every home/mobile client is), since it’s usually the client, not the server, that needs to keep the mapping open.aws ssm send-command: this is how a new client gets registered on the server — instead of connecting to the box to runwg setby hand, this uses AWS Systems Manager Run Command to execute that one command remotely, authenticated through IAM. Since SSH was never opened (Section 7), this is the only way this script has to reach the server — not an alternative to SSH, but the actual mechanism.wg set wg0 peer ... allowed-ips ...: this adds a peer to the running WireGuard interface without restarting it — WireGuard supports live reconfiguration. Combined withSaveConfig = truefrom the server config, this change also gets persisted back towg0.confautomatically.
Run it:
chmod +x scripts/add_client.sh
./scripts/add_client.sh laptop
File: scripts/generate-qr.py
#!/usr/bin/env python3
"""Generate a QR code from a WireGuard client config for easy mobile import."""
import sys
import qrcode
def main():
if len(sys.argv) != 2:
print("Usage: generate-qr.py <config-file>")
sys.exit(1)
with open(sys.argv[1], "r") as f:
config_text = f.read()
img = qrcode.make(config_text)
output_path = sys.argv[1].replace(".conf", "_qr.png")
img.save(output_path)
print(f"QR code saved to {output_path}")
if __name__ == "__main__":
main()
WireGuard’s mobile apps (iOS/Android) can import a config by scanning a QR code instead of transferring the .conf file manually — genuinely useful, not just a gimmick, since it avoids emailing yourself a file containing a private key.
pip install qrcode[pil]
python3 scripts/generate-qr.py laptop.conf
13Step 8 — Testing the Connection
On your client machine:
sudo wg-quick up ./laptop.conf
Check the tunnel is actually up:
sudo wg show
You should see a latest handshake timestamp — if this field is blank or missing, the handshake never completed (see Troubleshooting). Confirm your traffic is actually routed through the tunnel:
curl ifconfig.me
This should now print your VPN server’s public IP, not your real one. If it still shows your original IP, the tunnel came up but routing isn’t correctly sending traffic through it — check AllowedIPs = 0.0.0.0/0 is set on the client’s peer block.
Tear the tunnel down when done testing:
sudo wg-quick down ./laptop.conf
14Step 9 — Accessing and Hardening the Server
Connecting to the instance (there is no SSH port to connect to):
Since the security group never opens port 22, the way to get a shell on the box is:
aws ssm start-session --target <instance-id>
This works because of the IAM role attached in iam.tf (Section 8) — every session is authenticated by IAM and logged in CloudTrail, with no key pair to lose or leak and no open port for scanners to find. This isn’t an optional hardening step layered on afterward; it’s the only access path this project has from the start.
Beyond that default posture, and what’s already built in (IMDSv2, encrypted volume, minimal open ports), a few more steps are worth doing if you want to take this further:
Automatic security patching:
apt-get install -y unattended-upgrades
dpkg-reconfigure -plow unattended-upgrades
Add this to the user_data script so it’s applied on every fresh deploy.
Fail2ban, only if you deliberately open SSH for debugging:
apt-get install -y fail2ban
Fail2ban watches auth logs and temporarily bans IPs after repeated failed login attempts. It’s irrelevant as long as SSH stays closed — it’s included here in case you ever add a temporary SSH ingress rule while debugging and want to close that hole back down.
Rotate the server’s host key material periodically by tainting and re-applying the instance:
terraform taint module.vpn_instance.aws_instance.vpn_server
terraform apply
Because the Elastic IP is a separate resource from the instance (Section 8), this replaces the underlying box — getting fresh WireGuard keys and a fresh OS — while every client’s Endpoint = line keeps working, since the IP doesn’t change. You would then re-run add_client.sh for each device to re-register them against the new server key, or better, keep client AllowedIPs assignments in SSM instead of a local .client_counter file so a redeploy can restore them automatically.
15Troubleshooting Guide
Handshake never completes (sudo wg show shows no “latest handshake”):
- Check the security group actually allows UDP 51820 inbound from 0.0.0.0/0.
- Check the client’s Endpoint line has the correct public IP and port.
- Some corporate/public Wi-Fi networks block outbound UDP entirely — try mobile data as a control test.
Handshake completes, but no internet access through the tunnel:
- Confirm net.ipv4.ip_forward=1 actually took effect: sysctl net.ipv4.ip_forward should print 1.
- Confirm the MASQUERADE iptables rule is present: sudo iptables -t nat -L -n -v on the server.
- Confirm the client’s AllowedIPs = 0.0.0.0/0 (not a narrower range).
terraform apply recreates the instance every time even with no changes:
- Usually caused by user_data content changing between runs in a way Terraform detects as a diff (e.g., a templatefile() interpolation pulling in a value that changes every plan, like a timestamp). Keep user_data inputs static/deterministic.
Client connects but disconnects after a few minutes, especially on mobile data:
- Almost always a missing or too-long PersistentKeepalive on the client config. Confirm it’s set to 25.
aws ssm start-session or add_client.sh’s aws ssm send-command fails with an access error:
- Confirm the EC2 instance still has the IAM instance profile from iam.tf attached, and that the SSM Agent (bundled by default on modern Ubuntu AMIs) is running — check via aws ssm start-session --target <instance-id> and then systemctl status amazon-ssm-agent once connected.
16Cleanup
To avoid ongoing AWS charges when you’re done experimenting:
cd environments/dev
terraform destroy
Review the destroy plan carefully — this removes the Elastic IP too, so any client configs pointing at that IP become permanently invalid.
17Where to Go From Here
Once this base project works end-to-end, these extensions make it noticeably stronger as a portfolio piece:
- Monitoring: this repo doesn’t ship any monitoring by default. A natural next step is installing the CloudWatch agent in
user_datato track CPU, network throughput, and disk usage, plus a small cron job pushing a customConnectedPeersmetric (wg show wg0 peers | wc -l) so you have a graphable signal for how many devices are actually connected. - CI/CD: wire
terraform plan/terraform applyinto a pipeline (GitHub Actions, GitLab CI, Jenkins, whatever you already use) with a manual approval gate beforeapply— the same principle as any production infrastructure pipeline:planruns automatically so you always see what would change, but a human approves before it goes live. - Multi-region failover: a second WireGuard server in another region, with Route 53 health-check-based failover routing.
- Site-to-site mode: instead of individual client peers, connect two entire private networks (e.g., a home lab and a cloud VPC) through the tunnel.
- Replace the manual
add_client.shcounter logic with state kept in DynamoDB or SSM, so client IP assignment survives across machines and team members instead of relying on a local.client_counterfile.