Amazon VPC and Subnets
An Amazon Virtual Private Cloud (VPC) is your own isolated network inside an AWS Region. You choose its private IP address range, divide it into subnets, and decide how traffic flows in and out. Almost every resource with a network interface (EC2, RDS, Lambda in a VPC, load balancers, ECS tasks) lives in a subnet of a VPC.
CIDR blocks in two minutes
IP ranges are written in CIDR notation: 10.0.0.0/16 means "the first 16 bits are fixed, the remaining 16 bits are free", which is 2^16 = 65,536 addresses. A larger number after the slash means a smaller network.
| CIDR | Addresses | Typical use |
|---|---|---|
/16 |
65,536 | A whole VPC (the largest allowed) |
/20 |
4,096 | A large subnet |
/24 |
256 | A typical subnet |
/28 |
16 | The smallest allowed subnet |
Use the private ranges from RFC 1918 (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16) and avoid overlapping with your office network or other VPCs you may want to connect later.
Python's standard library has everything needed to explore CIDR blocks:
import ipaddress
vpc = ipaddress.ip_network("10.0.0.0/16")
print(vpc, "has", vpc.num_addresses, "addresses")
print("first:", vpc[0], " last:", vpc[-1])
print("is private:", vpc.is_private)
for cidr in ["10.0.1.0/24", "10.0.200.16/28", "192.168.1.0/24"]:
net = ipaddress.ip_network(cidr)
print(f"{cidr:<15} {net.num_addresses:>5} addresses, inside VPC: {net.subnet_of(vpc)}")10.0.0.0/16 has 65536 addresses
first: 10.0.0.0 last: 10.0.255.255
is private: True
10.0.1.0/24 256 addresses, inside VPC: True
10.0.200.16/28 16 addresses, inside VPC: True
192.168.1.0/24 256 addresses, inside VPC: False
Subnets
A subnet is a slice of the VPC's range that lives in one Availability Zone. A subnet is called:
- public if its route table sends
0.0.0.0/0to an internet gateway (resources with public IPs are reachable from the internet); - private if it has no such route (resources can reach the internet only through a NAT gateway, if at all).
AWS reserves five addresses in every subnet: the network address, .1 (VPC router), .2 (DNS), .3 (reserved for future use) and the broadcast address. A /24 therefore has 251 usable addresses, and a /28 only 11.
Model: planning subnets for three AZs
A common layout: for each of three AZs, one public subnet (load balancers, NAT gateways) and two private ones (application, database). subnets() cuts the VPC into equal pieces:
import ipaddress
vpc = ipaddress.ip_network("10.20.0.0/16")
azs = ["eu-west-1a", "eu-west-1b", "eu-west-1c"]
tiers = ["public", "app", "data"]
blocks = vpc.subnets(new_prefix=20) # 16 blocks of 4,096 addresses
plan = []
for tier in tiers:
for az in azs:
plan.append((tier, az, next(blocks)))
print(f"{'tier':<7}{'AZ':<12}{'CIDR':<16}{'usable':>7}")
for tier, az, net in plan:
print(f"{tier:<7}{az:<12}{str(net):<16}{net.num_addresses - 5:>7}")
spare = list(blocks)
print(f"spare /20 blocks for later: {len(spare)} (next free: {spare[0]})")tier AZ CIDR usable
public eu-west-1a 10.20.0.0/20 4091
public eu-west-1b 10.20.16.0/20 4091
public eu-west-1c 10.20.32.0/20 4091
app eu-west-1a 10.20.48.0/20 4091
app eu-west-1b 10.20.64.0/20 4091
app eu-west-1c 10.20.80.0/20 4091
data eu-west-1a 10.20.96.0/20 4091
data eu-west-1b 10.20.112.0/20 4091
data eu-west-1c 10.20.128.0/20 4091
spare /20 blocks for later: 7 (next free: 10.20.144.0/20)
Leaving spare blocks is deliberate: you can't resize a subnet later, but you can add new subnets in unused space.
Creating a VPC with the CLI
aws ec2 create-vpc --cidr-block 10.20.0.0/16 \
--tag-specifications 'ResourceType=vpc,Tags=[{Key=Name,Value=shop-vpc}]'
aws ec2 create-subnet --vpc-id vpc-0abc1234def567890 --cidr-block 10.20.0.0/20 \
--availability-zone eu-west-1a
aws ec2 describe-subnets --filters Name=vpc-id,Values=vpc-0abc1234def567890 \
--query "Subnets[].[SubnetId,CidrBlock,AvailabilityZone,AvailableIpAddressCount]" --output tableSample output:
--------------------------------------------------------------------------
| DescribeSubnets |
+---------------------------+----------------+-------------+-------------+
| subnet-0aa11bb22cc33dd44 | 10.20.0.0/20 | eu-west-1a | 4091 |
| subnet-0ee55ff66aa77bb88 | 10.20.16.0/20 | eu-west-1b | 4091 |
+---------------------------+----------------+-------------+-------------+In the console, the "VPC and more" wizard creates the VPC, subnets, route tables and gateways in one step.
Model: checking for overlapping ranges
Two VPCs with overlapping ranges can't be connected with VPC peering or Transit Gateway routing. Check before you allocate:
import ipaddress
from itertools import combinations
networks = {
"office": "192.168.0.0/20",
"shop-vpc": "10.20.0.0/16",
"data-vpc": "10.30.0.0/16",
"legacy-vpc": "10.20.128.0/17",
"partner-vpn": "172.16.4.0/22",
}
nets = {name: ipaddress.ip_network(c) for name, c in networks.items()}
clashes = [(a, b) for a, b in combinations(nets, 2) if nets[a].overlaps(nets[b])]
for a, b in clashes:
print(f"OVERLAP: {a} {nets[a]} and {b} {nets[b]}")
print(f"{len(clashes)} overlap(s) among {len(nets)} networks")OVERLAP: shop-vpc 10.20.0.0/16 and legacy-vpc 10.20.128.0/17
1 overlap(s) among 5 networks
Test yourself
How many addresses does a /24 subnet contain, and how many can you use in AWS?
- 256 and 256
- 256 and 251
- 254 and 250
- 24 and 19
What makes a subnet 'public'?
- Its name
- A route to an internet gateway in its route table
- A /16 CIDR
- Being in us-east-1
A subnet spans ...
- One Availability Zone
- All AZs of the Region
- Several Regions
- One EC2 instance