What Is an AWS VPC? CIDR Planning, Public, Private and Isolated Subnets, NAT Gateways, Route Tables and Endpoints, Tested with Terraform and No AWS Bill

One changed line gave three private AWS subnets a route to the internet gateway. Apply still completed. CIDR plan, NAT, endpoints and the tests that caught it.

By Mirac Can Yılmaz 30 min read
What Is an AWS VPC? CIDR Planning, Public, Private and Isolated Subnets, NAT Gateways, Route Tables and Endpoints, Tested with Terraform and No AWS Bill - DevOps yazısının kapak görseli

I changed one line in an AWS VPC module and applied it. terraform validate passed, the plan said 60 to add, and the run ended with Apply complete! Resources: 60 added, 0 changed, 0 destroyed. All three subnets I had named private now had a default route to the internet gateway. Nothing refused it, because nothing in AWS knows what "private" means. A subnet is private only because of where its route table points, and the route table had just been told to point somewhere else.

Two things caught it, and neither was the apply. A terraform test file with a mocked provider failed before anything existed, and a script that reads the network back through describe-* calls failed after. This post is about the network those checks protect: how to plan a CIDR, what makes a subnet public, private or isolated, where NAT gateways go and what one costs you in availability, how route tables, security groups, NACLs and endpoints fit together, and the subnet tags EKS will look for later.

One thing up front. No AWS account was used. Everything ran against LocalStack on a laptop and against Terraform's own mocks. That checks the shape of the API calls and the intent of the code. It does not route a packet, and I will not claim it did. There is a section on exactly where the emulator stops.

What is an AWS VPC?

A Virtual Private Cloud (VPC) is a private network you define inside one AWS region. You pick an IP range for it, cut that range into subnets, and decide which subnets can talk to the internet and how. Nothing gets in or out unless a route and a firewall rule both allow it.

The pieces, in the order you meet them:

  • VPC: the range itself, for example 10.24.0.0/16. Regional.
  • Subnet: a slice of that range that lives in exactly one Availability Zone (AZ).
  • Route table: a list of "traffic for this destination goes to that target". Every subnet uses exactly one.
  • Internet gateway (IGW): the door between the VPC and the internet. One per VPC.
  • NAT gateway: lets private subnets start connections to the internet without being reachable from it.
  • Security group: a stateful firewall on a network interface.
  • Network ACL (NACL): a stateless firewall on a subnet.
  • VPC endpoint: a private path to an AWS service, so that traffic does not need the internet at all.

The problem, and why it matters

Most teams meet the VPC once, on the day the account is created. Somebody clicks through a wizard or copies a module, it works, and the network becomes the thing nobody touches. Then the questions arrive one at a time. Can we peer with the data team's account? Not if both sides picked 10.0.0.0/16. Why is the NAT line on the bill so large? Because every image pull and every S3 upload from a private subnet goes through it. Why did one zone's outage take the whole service's outbound traffic with it? Because there was one NAT gateway, and it lived in that zone.

None of these are exotic. They are decisions that were made by default on day one and that are expensive to change later, because a subnet's CIDR cannot be edited and a VPC's range cannot be swapped under running workloads.

The second half of the problem is that the network is hard to test. A wrong route does not fail the apply. A security group that is too open does not fail the apply. The API accepts them, the pipeline is green, and the mistake waits for an incident or an audit. Most teams test this by applying to a sandbox account and looking, which needs an account, costs money while it runs, and still relies on someone looking at the right thing.

So I wanted two things from this lab: a layout I can defend line by line, and checks that fail when the layout stops being what I meant, on a laptop, with no cloud bill.

What a planned VPC gives you

In practice What I saw in the lab
A CIDR from an address plan ranges that never overlap another VPC you will connect to prod on 10.24.0.0/16, stage on 10.25.0.0/16, upper half of each left free
Three tiers load balancers, workloads and databases have different exposure by construction public, private and isolated subnets in three zones, nine in total
One private route table per zone egress stays in its zone; changing the NAT layout later only edits routes single to per_az planned 4 adds and 2 route updates, no subnet replaced
Gateway endpoints S3 and DynamoDB traffic stays off the NAT gateway the endpoint routes appeared in every private and isolated route table
Tags for EKS the cluster finds the right subnets for load balancers without being told kubernetes.io/role/elb on public, kubernetes.io/role/internal-elb on private
Intent tests a wiring mistake fails before the apply, with a sentence that says what is wrong three one-line bugs, all accepted by the API, all caught

The cost: the module is longer than the wizard, a NAT gateway per zone is three hourly charges instead of one, and the tests have to be kept true as the module changes.

How it works: one VPC, three zones, three tiers

Diagram: a VPC 10.24.0.0/16 across us-east-1a, 1b and 1c. Top row, public subnets 10.24.96.0/24 to 10.24.98.0/24, each holding a NAT gateway and tagged kubernetes.io/role/elb=1, sharing one route table whose 0.0.0.0/0 goes to the internet gateway. Middle row, private subnets 10.24.0.0/19, 10.24.32.0/19 and 10.24.64.0/19, each with its own route table sending 0.0.0.0/0 to the NAT gateway in the same zone and S3 and DynamoDB to a gateway endpoint, tagged kubernetes.io/role/internal-elb=1. Bottom row, isolated subnets 10.24.100.0/24 to 10.24.102.0/24 with no default route. The upper half 10.24.128.0/17 is unallocated. Three notes compare nat_strategy per_az, single and none.

CIDR planning

The VPC range is the one decision you cannot take back, so it deserves five minutes.

  • Size. AWS allows a VPC between /16 and /28. A /16 looks wasteful until you run Kubernetes on it: with the default AWS VPC CNI every pod takes an address from the subnet, so a private subnet fills at the speed of pods, not instances. Small VPCs are fine for small, fixed things. For a platform, I take the /16.
  • No overlap, ever. Two VPCs with overlapping ranges cannot be peered, and a Transit Gateway cannot route between them sensibly. Keep a list. Mine is one line per environment: prod 10.24.0.0/16, stage 10.25.0.0/16. The office network and the VPN pool belong on the same list.
  • Five addresses are not yours. In every subnet AWS reserves the first four addresses and the last one: network address, VPC router, DNS, one reserved for future use, and broadcast. A /24 gives you 251, and the smallest subnet AWS documents, a /28, gives you 11.
  • Leave room. The module uses the lower half of the /16 and leaves 10.24.128.0/17 unallocated. A fourth tier or a second cluster will want addresses, and a subnet cannot be resized.
  • Unequal tiers. Private subnets are /19 because that is where pods live. Public subnets are /24 because they hold load balancers and NAT gateways and little else. Isolated subnets are /24 because databases are few.

Public, private, isolated

The three names are conventions. What AWS actually has is route tables.

  • A subnet is public when its route table sends 0.0.0.0/0 to the internet gateway. Instances with a public IP are reachable from outside, if a security group allows it.
  • A subnet is private when 0.0.0.0/0 goes to a NAT gateway. Things inside can start connections outward; nothing outside can start one inward.
  • A subnet is isolated when there is no 0.0.0.0/0 route at all. It can talk to the rest of the VPC and to whatever has an endpoint.

A subnet with no explicit association uses the VPC's main route table. That is a quiet trap: forget one association and the subnet inherits whatever the main table says. The module associates every subnet explicitly and leaves the main table with only the local route, so a forgotten subnet ends up dark, not public.

NAT gateways: per zone, single, or none

A NAT gateway is a zonal resource. It sits in one public subnet, in one zone, with one Elastic IP. The module takes the layout as a variable:

nat_for_az = {
  for k in local.az_keys : k => (
    var.nat_strategy == "per_az" ? k :
    var.nat_strategy == "single" ? local.az_keys[0] : null
  )
}

per_az gives each private route table the NAT gateway in its own zone. single points all three at the gateway in zone a. none creates no gateway and no default route. With single, two of the three zones send their outbound traffic across a zone boundary. AWS charges for data that crosses zones, on top of the NAT gateway's own per-gigabyte processing charge, and if zone a has a bad day, the healthy zones lose their way out as well. With per_az you pay the hourly charge three times and a zone failure stays in its zone. I am keeping this qualitative on purpose; the current numbers are on the Amazon VPC pricing page, and they change.

Security groups and NACLs

Two firewalls, and they behave differently.

A security group is stateful. If it allows a connection in, the reply is allowed out without a rule, and the other way round. Rules are allow-only, and a rule can name another security group instead of a CIDR. In the module the database group allows 5432 from the application group, not from 10.24.0.0/19. Add a subnet tomorrow and the rule still holds, because it follows group membership.

A NACL is stateless and attached to a subnet. It evaluates numbered rules in order, it can deny, and it knows nothing about connections. A request in on 5432 needs an inbound rule, and its reply needs an outbound rule for the client's ephemeral port, which is why the isolated tier's NACL allows 1024-65535 outbound to the private subnets. Forgetting that return path is the classic NACL outage: the request arrives, the reply is dropped, and the application sees a timeout.

The default security group of a new VPC allows everything between its members. The module empties it, so anything that lands in it by accident can talk to nothing.

VPC endpoints

A gateway endpoint exists for S3 and DynamoDB. It is not a network interface; it is an entry in a route table whose destination is a prefix list for the service. Traffic to S3 from a subnet with that route goes to the endpoint, not to the NAT gateway, and gateway endpoints carry no hourly charge. It only works for route tables it is attached to, which is the part people forget.

An interface endpoint is a network interface in your subnet, one per zone, with a security group in front of it and a private DNS name that makes ecr.us-east-1.amazonaws.com resolve to a private address. It exists for most other services, and each one is billed per hour and per gigabyte. That is why the module creates the gateway endpoints by default and takes interface endpoints as a list.

Flow logs and EKS tags

A flow log records accepted and rejected connections for a VPC, subnet or interface, to CloudWatch Logs or S3. It is the first thing you want during an incident and it is not on by default. The module turns it on for the whole VPC with a short retention.

EKS finds subnets by tag. The AWS Load Balancer Controller puts internet-facing load balancers in subnets tagged kubernetes.io/role/elb = 1 and internal ones in subnets tagged kubernetes.io/role/internal-elb = 1. Without the tags the controller has to guess, or be told per load balancer with an annotation. The isolated tier gets neither tag, so Kubernetes is never offered a database subnet.

The lab

A small Terraform module with no registry dependency, a root configuration that points it at LocalStack 4.9 on 127.0.0.1:4630, two terraform test files, and a Python script that asserts intent over describe-* output. Every script starts by unsetting the AWS credential variables, pointing the config and credentials files into the lab's scratch folder and refusing to run if the endpoint is not loopback. The provider has dummy keys and every skip_* flag. The laptop this ran on has a real AWS login, and the lab cannot use it.

1. Tests first, with nothing running

terraform test (Terraform 1.6 and later) runs assertions against a plan or an apply. Since 1.7 it can mock the provider: mock_provider "aws" {} replaces every API call with generated values. An apply under a mock creates nothing, but every resource gets an id, so a test can ask about wiring:

run "nat_per_az_keeps_traffic_in_its_zone" {
  command = apply
  assert {
    condition     = alltrue([for k, r in aws_route.private_default :
                             r.nat_gateway_id == aws_nat_gateway.this[k].id])
    error_message = "Each private route table's default route must point at the NAT gateway in the same AZ."
  }
}

No Docker, no emulator, no credentials. This is the part that runs on every pull request.

Terminal: terraform test in modules/vpc. Eleven runs pass: address_plan, nat_per_az_keeps_traffic_in_its_zone, private_default_route_is_never_the_internet_gateway, every_subnet_has_an_explicit_route_table, gateway_endpoints_cover_private_and_isolated, eks_can_find_the_subnets, single_nat_is_one_gateway_for_everyone, no_nat_means_no_default_route, rejects_a_vpc_too_small_to_split, rejects_a_single_az, rejects_an_unknown_nat_strategy. Then terraform test in live: prod_refuses_a_single_nat, prod_gets_one_nat_per_az, dev_may_share_one_nat, refuses_a_remote_endpoint, all pass.

The first run did not look like that. It failed on "log_destination" (ftud4qb9) is an invalid ARN: arn: invalid prefix. A mock fills computed attributes with random strings, the flow log resource takes the log group's ARN as an argument, and the real provider schema still validates that argument. override_resource with an ARN-shaped value fixed it. The same run also failed two of my own assertions, one because my CIDR arithmetic was wrong and one because I was asserting on an attribute that is unknown at plan time. Tests need testing too.

2. Apply to LocalStack and read it back

The apply creates 60 resources. Then the script asks the API what it has.

Terminal: describe-subnets lists nine subnets with zone, CIDR and free addresses: p24-isolated-a to c on 10.24.100.0/24 to 10.24.102.0/24 with 251 free each; p24-private-a to c on 10.24.0.0/19, 10.24.32.0/19, 10.24.64.0/19 with 8186 free each; p24-public-a to c on 10.24.96.0/24 to 10.24.98.0/24 with 250 free each. describe-route-tables shows the main table with only the local route, p24-isolated with local plus two prefix-list routes to vpce ids, each p24-private table with 0.0.0.0/0 to its own nat id plus the two endpoint routes, and p24-public with 0.0.0.0/0 to the igw.

The free address column is the reserved-five rule showing up without being asked. A /24 has 256 addresses and reports 251 in the isolated tier. The public subnets report 250, because each holds a NAT gateway's network interface. The private /19 has 8,192 addresses, loses five, and loses one more to the interface endpoint.

A second plan was not clean. Three security group rules wanted an in-place update every time, 000000000000/sg-… back to sg-…. My reading of the provider is that it strips its own account id from a referenced group, and with skip_requesting_account_id = true it does not know its account id. I did not flip the flag to prove it, because that flag is one of the things keeping this lab away from a real account. The script accepts exactly that diff and fails on any other.

3. Assert the intent, not the resource count

"60 added" says nothing about whether the 60 are wired correctly. The verification script reads subnets, route tables, NAT gateways, endpoints, security groups, NACLs and flow logs, and checks relationships.

Terminal: verify.py against the applied VPC with expect-nat per_az. 34 PASS lines, among them: every subnet CIDR is inside the VPC CIDR, no two subnets overlap, no subnet falls back to the VPC main route table, p24-public-a 0.0.0.0/0 to internet gateway, every NAT gateway sits in a public subnet, p24-private-b (us-east-1b) 0.0.0.0/0 to NAT in the same AZ, p24-isolated-a no default route, s3 gateway endpoint is on every private and isolated route table, default security group has no rules, db security group ingress only from the app security group, isolated NACL outbound ephemeral ports, public subnets tagged kubernetes.io/role/elb=1, VPC flow log is ACTIVE. Last line OK: 0 failed.

The check I care most about is the one in the middle: for each private subnet, follow the default route to its NAT gateway, look up which subnet that gateway is in, and compare zones. No single resource holds that fact.

4. Mistakes the API refuses

Some mistakes do fail, and it is worth knowing where. A subnet that overlaps another, and a subnet outside the VPC range:

Terminal: aws ec2 create-subnet with 10.24.16.0/20 returns An error occurred (InvalidSubnet.Conflict) when calling the CreateSubnet operation: The CIDR '10.24.16.0/20' conflicts with another subnet. create-subnet with 10.25.0.0/24 returns InvalidSubnet.Range: The CIDR '10.25.0.0/24' is invalid. create-vpc with 10.0.0.0/8 returns InvalidVpc.Range. Then through Terraform: terraform plan for each case prints Plan: 1 to add, and terraform apply stops with Error: creating EC2 Subnet: operation error EC2: CreateSubnet, https response error StatusCode: 400, api error InvalidSubnet.Conflict. Last, two plan-time refusals: cidr must be a valid IPv4 CIDR of /20 or larger, and prod must use nat_strategy = per_az.

The line to notice is in the middle. terraform plan printed Plan: 1 to add for both bad subnets. Plan does not ask the API whether a CIDR is free; apply does. A green plan in a pull request does not mean the address plan is valid. Variable validation, the last two errors in the image, is how you move that knowledge to plan time.

5. Mistakes the API accepts

Now the opening story. Three bugs, each one line, each the kind of thing a refactor produces:

  1. igw-route: the private default route gets gateway_id = aws_internet_gateway.this.id where it had nat_gateway_id.
  2. nat-in-private: the NAT gateway is created in aws_subnet.private where it should be aws_subnet.public.
  3. pay-three-use-one: the route looks up aws_nat_gateway.this[local.az_keys[0]], so three gateways exist and every zone uses the first.

For each, the script runs what a reviewer would see, then what the API says, then the two checks.

Terminal: bug igw-route. The diff shows nat_gateway_id = aws_nat_gateway.this[each.value].id replaced by gateway_id = aws_internet_gateway.this.id. terraform validate: Success! The configuration is valid. terraform plan: Plan: 60 to add, 0 to change, 0 to destroy. terraform apply: Apply complete! Resources: 60 added. Then terraform test, mocked: two runs fail, nat_per_az_keeps_traffic_in_its_zone and private_default_route_is_never_the_internet_gateway, the second with the message "A private route table has a default route to the internet gateway. That subnet is public now, whatever its name says." Then verify.py on the applied copy: FAIL p24bug-private-a: no route to an internet gateway, and the same for b and c, NOT OK: 6 failed.

validate is satisfied because the code is valid. The plan count is identical to the good module. The apply completes. As far as I know the real API behaves the same way, because a route table does not know what you call the subnet. I did not reproduce it against real AWS for this post.

Terminal: bug pay-three-use-one. The diff shows aws_nat_gateway.this[each.value].id replaced by aws_nat_gateway.this[local.az_keys[0]].id. validate succeeds, Plan: 60 to add, Apply complete. terraform test: run nat_per_az_keeps_traffic_in_its_zone fail, Each private route table's default route must point at the NAT gateway in the same AZ. verify.py: FAIL p24bug-private-b (us-east-1b): 0.0.0.0/0 to NAT in the same AZ, NAT is in us-east-1a: egress crosses a zone boundary and dies with that zone; the same for private-c; NOT OK: 2 failed.

The third bug is the one I find most uncomfortable. Nothing is exposed and everything works. You pay for three NAT gateways, two sit idle, and the first zone failure shows that the redundancy was only in the bill.

6. One variable, three network shapes

A second VPC, stage, on 10.25.0.0/16, starts with nat_strategy = "single".

Terminal: terraform plan with environment=prod and nat_strategy=single fails with "prod must use nat_strategy = per_az. single is allowed in dev and stage only: one NAT gateway is one AZ's failure away from no egress." With environment=stage the apply completes; the route listing shows p24stg-private-a in us-east-1a using a NAT in us-east-1a, and private-b and private-c using the same NAT in us-east-1a, marked "leaves its zone". verify.py with expect-nat single passes. verify.py with expect-nat per_az fails: NAT gateways expected 3 found 1, and two private subnets whose egress crosses a zone boundary. Then the plan for per_az lists two aws_eip and two aws_nat_gateway to be created and private_default b and c updated in-place, after which each private subnet uses the NAT in its own zone.

Three things in that image:

  • The policy is code. The root configuration has a validation that reads both environment and nat_strategy. Production with a single NAT gateway does not plan. Anyone who wants that has to change the line, in a pull request, with a name on it.
  • The same script, a different expectation. verify.py --expect-nat per_az fails the stage VPC and names the two zones whose traffic leaves its zone. With --expect-nat single it passes and says the same thing as a note. The layout is a choice; the check makes it a recorded choice.
  • Growing up is cheap, if the module was built for it. Moving from single to per_az planned four additions and two route updates. (The plan line in the image reads 5 to change; three of those are the security group diff from step 2.) No subnet and no route table was replaced, because the module creates one private route table per zone even when all three point at the same gateway.

The last step sets nat_strategy = "none". The gateways, their addresses and the three default routes are destroyed, and what remains reachable from a private subnet is S3, DynamoDB and the one interface endpoint. That is a real design for workloads that only talk to AWS services, and a non-starter for anything that pulls from a public registry.

7. Where the emulator stops

This is the section the whole approach depends on. I wrote seven probes, each for something the EC2 documentation says is refused or shown as a state, and ran them against LocalStack 4.9 community.

Terminal: seven probes. 1, create-subnet 10.99.1.0/29 returns available with 3 free addresses. 2, create-subnet with availability zone eu-west-1a in us-east-1 returns available. 3, a default route to a NAT gateway that is then deleted: nat gateway state deleted, route state still active. 4, create-route to nat-0000000000000dead returns True, while the same call with a fake internet gateway is refused with InvalidInternetGatewayID.NotFound. 5, VPC peering between two VPCs both 10.99.0.0/16 reaches status active. 6, create-network-insights-path returns "The create_network_insights_path action has not been implemented". 7, the flow log is ACTIVE and the log group has 0 log streams. Each probe prints PASS gap confirmed.

Read that list as "things a green local run did not check":

  • A /29 subnet was created. AWS documents /28 as the smallest.
  • A zone from another region was accepted.
  • After the NAT gateway was deleted, the route to it still said active. On AWS that route is documented to show blackhole, which is the state you search for when a private subnet loses its way out.
  • A route to a NAT gateway id that never existed was accepted.
  • Two VPCs with the same CIDR were peered and the peering went active. AWS documents that as not possible. The emulator will not protect your address plan; the check has to be yours.
  • Reachability Analyzer is not implemented, so "can A reach B" cannot be asked.
  • The flow log exists and is ACTIVE, and no record is ever written, because no packet ever flows.

The phase passes while those gaps exist. If a LocalStack upgrade closes one, the phase fails and tells me the list in this post is out of date. AWS has since published its own local emulator; how it compares to LocalStack is in the previous post.

Limits and rules you only learn by hitting them

  • A subnet's CIDR and zone are fixed. Changing either is a replacement, which means moving everything in it. Plan the tiers once.
  • A VPC can take secondary CIDRs, with restrictions on which ranges may be added to which primary. It is an escape hatch, and it makes the address plan harder to read.
  • 100.64.0.0/10 is the usual answer when pods run out of addresses: a secondary range for pod networking that the rest of the company does not route. It is a deliberate design, not a default.
  • Quotas are per region and start small. VPCs per region, Elastic IPs, NAT gateways per zone, routes per route table and rules per security group all have default quotas. A per_az layout in three zones needs three Elastic IPs before anything else asks for one.
  • A gateway endpoint adds a route to every route table it is attached to, and that route counts against the table's quota.
  • Security group rules are allow-only. To block one address you need a NACL, which is why NACLs survive in designs that would rather not have them.
  • NACL rule numbers are evaluated lowest first and the first match wins. Leave gaps between numbers.
  • map_public_ip_on_launch is a subnet setting, not a security boundary. A private subnet with it enabled hands out public addresses that go nowhere; a public subnet with it disabled still routes to the IGW for anything that has an Elastic IP.
  • DNS needs both enable_dns_support and enable_dns_hostnames for private DNS on interface endpoints.
  • Mocked tests see your code, not the provider's behaviour. A mock will hand back whatever you wrote. It cannot tell you that an argument is ignored, that an API call is refused, or that two resources race.
  • terraform test with command = apply on a real provider creates real things and destroys them at the end. Against a paid account that is a bill and a cleanup risk; against a mock it is free.

Moving a fleet, not a lab

One VPC is a lab. Twenty accounts with a VPC each is where the address plan earns its keep.

  1. Start with the list. Every existing VPC, every on-premises range, every VPN pool, in one file in Git. Overlaps found on paper are free; overlaps found during a peering request are a migration.
  2. Allocate, do not choose. New VPCs get the next free block from the list. AWS IPAM does this as a service; a reviewed text file does it for a small organisation. What matters is that nobody types a CIDR from memory.
  3. One module, pinned. Environments consume the VPC module at a version, the same way the pipelines in the reusable workflows post consume a shared workflow at a tag. A change to the module is a pull request with the mocked tests running on it.
  4. Policy lives in the root, not in a wiki. "Prod uses a NAT gateway per zone" is a validation block. "Dev may use one" is the same block. A wiki page does not fail a plan.
  5. Verification runs after every apply. The same describe-* assertions, pointed at the real account with read-only credentials, in the pipeline step after the apply. This is the part of the lab that carries over unchanged, and against real AWS it also sees blackhole routes.
  6. Existing VPCs are imported, not recreated. Write the module to match what exists, import it, get to an empty plan, and only then change things. The ordering rules from the depends_on post apply: a NAT gateway replacement is a destroy and a create unless you say otherwise.
  7. Split state by blast radius. The network changes rarely and breaks everything when it does. It gets its own state, and the things that live in it read its outputs, as in the Terragrunt post.

What this does not solve: connectivity between the VPCs, DNS across accounts, and inspection of traffic between them. Those are Transit Gateway, Route 53 Resolver and firewall topics, and each has its own bill.

Frequently asked

What is the difference between a public and a private subnet in AWS? The route table. A public subnet's route table sends 0.0.0.0/0 to an internet gateway; a private subnet's sends it to a NAT gateway, or nowhere. The name, the tag and the "auto-assign public IP" setting do not decide it.

Do I need a NAT gateway in every Availability Zone? For production, I do it. With one gateway, a failure in its zone removes outbound internet access from every zone, and traffic from the other zones pays to cross a zone boundary on the way. For development environments one gateway is a reasonable saving.

How many IP addresses can I use in a /24 subnet? 251. AWS reserves the first four and the last one in every subnet, whatever its size.

Security group or NACL, which one should I use? Security groups for almost everything: they are stateful, attached to the workload, and can reference each other. NACLs when you need an explicit deny or a subnet-wide guard rail, and then with the return traffic on ephemeral ports allowed.

Does a VPC endpoint replace a NAT gateway? Only for the services that have endpoints and only if that is all the workload talks to. A gateway endpoint for S3 and DynamoDB takes that traffic off the NAT gateway at no hourly cost. Pulling an image from a public registry still needs a way out.

Can I change a VPC's CIDR later? You can add secondary ranges. You cannot change the primary range or resize a subnet. Moving to a new range means a new VPC and a migration.

Can I test a VPC without an AWS account? You can test the code and the API shape: terraform test with a mocked provider for wiring, an emulator for the calls. You cannot test reachability, performance or anything a packet would tell you. The section above lists what my local run accepted that AWS documents as refused.

Which tags does EKS need on subnets? kubernetes.io/role/elb = 1 on public subnets for internet-facing load balancers and kubernetes.io/role/internal-elb = 1 on private subnets for internal ones. Older setups also tag kubernetes.io/cluster/<name>.

Where it broke

1. "log_destination" (ftud4qb9) is an invalid ARN: arn: invalid prefix

The first terraform test run with mock_provider. The mock generated a random string for the log group's arn, and aws_flow_log validates its log_destination as an ARN. Fixed with override_resource on the log group and the IAM role, giving both an ARN-shaped value. Mocked values have to be valid wherever the real schema checks them.

2. Only public subnets may hand out public IPs on launch. (my own assertion, failing on correct code)

I asserted map_public_ip_on_launch == false on private subnets at plan time. The module did not set the attribute, so it was "known after apply", and an unknown value does not satisfy a condition. Setting it explicitly to false in the module fixed the test and made the module say what it means.

3. Plan: 0 to add, 3 to change, 0 to destroy, on every plan

referenced_security_group_id drifting between 000000000000/sg-… and sg-… on the three rules that reference another group. An artefact of running the provider with skip_requesting_account_id = true against the emulator, as far as I can tell from the provider's behaviour. I left the flag on and taught the stability check to accept exactly that diff.

4. InvalidSubnet.Conflict: The CIDR '10.24.16.0/20' conflicts with another subnet

After a green plan. terraform plan does not check whether a CIDR is free or inside the VPC. The module derives every subnet from the VPC range with cidrsubnet, so its own subnets cannot collide; a hand-written extra subnet can.

5. InvalidSubnet.Range: The CIDR '10.25.0.0/24' is invalid.

A subnet outside the VPC range. The message says "invalid", not "outside the VPC". Worth knowing when you search for it.

6. Apply complete! Resources: 60 added for a VPC with public "private" subnets

Not an error, which is the point of the post. The assertion that catches it is one line long.

7. scripts/env.sh:4: BASH_SOURCE[0]: parameter not set

My own shell. I sourced the lab's environment file from zsh, the script directory resolved to /, and the config files could not be written. The credential variables had already been unset and the endpoint was already loopback, so the calls that followed went to LocalStack. It is the reason every script in the lab now runs under bash explicitly, and the reason the guard is on the endpoint, not on the path.

8. SyntaxError: unexpected character after line continuation character

A Python one-liner inside a bash heredoc inside single quotes, with escaped double quotes. The stage VPC had already been applied when it failed, so the next run found a half-finished state. The route printer became its own file, and the phase now destroys whatever a previous run left behind before it starts.

The trade-off, side by side

NAT layout:

NAT gateway per zone Single NAT gateway No NAT, endpoints only
Plus a zone failure stays in its zone; no cross-zone hop for egress one hourly charge, one Elastic IP, simplest to reason about no NAT charge at all; nothing in the subnet can reach the internet, which is a security property
Minus the hourly charge and an Elastic IP in every zone, even when idle one zone's failure removes egress for all; other zones pay cross-zone data charges to reach it only services with an endpoint are reachable; every interface endpoint is its own hourly charge; public registries and third-party APIs are out
Where it fits production, and anything with an availability target dev, stage, short-lived environments data platforms and batch jobs that talk only to AWS services

Firewalls:

Security group Network ACL
State stateful: replies are allowed automatically stateless: the return path needs its own rule, on ephemeral ports
Attached to a network interface a subnet
Plus can reference other groups, so rules follow workloads; allow-only keeps it readable can deny; one rule covers everything in the subnet
Minus cannot deny; many groups on one interface are hard to audit ordered rule numbers; easy to break return traffic; coarse
Where it fits the default for every workload an explicit deny, or a guard rail around a sensitive tier

How to test the network code:

terraform test with mocks Apply to LocalStack A real sandbox account
Checks the wiring in your code that the API accepts the calls; ids, CIDR conflicts, tags, address counts everything, including packets
Plus no Docker, no credentials, runs on every pull request real provider, real API errors, describe-* scripts work unchanged reachability, blackhole routes, real quotas, flow log records
Minus sees only what you wrote; mocked values need shaping no data plane; accepted a /29, a deleted NAT target and an overlapping peering an account, a bill while it runs, cleanup, and someone still has to look
Where it fits every change to the module before merge, and for learning the API without a bill before production, and for anything about traffic

None of the columns is the answer by itself. In the lab the mocked tests gate the module, LocalStack shows that the calls are well-formed, and the describe-* script is the piece I would point at a real account next.

When to use which

  • Write the address list before the first VPC. It costs nothing on day one.
  • Three tiers, three zones as the default shape; drop a tier only when you can say why.
  • One private route table per zone from the start, even with a single NAT gateway. It makes the later change a route edit.
  • per_az for production, single elsewhere, and put the rule in code.
  • Gateway endpoints for S3 and DynamoDB always. Interface endpoints when the traffic or the security requirement justifies the hourly charge.
  • Security groups that reference groups; NACLs only where you need a deny.
  • Mocked tests on every pull request, an emulator before merge, read-only verification after every real apply.
  • Do not read a green local run as proof of reachability. It is proof of intent.

Your call

I run a NAT gateway per zone in production and a single one everywhere else, and I keep that rule in the root configuration, not in a document. That is for a platform with an availability target and a team that reads the bill; a three-person startup may reasonably choose one gateway and accept the risk. Two things I would like to hear from real accounts:

  • One NAT gateway or one per zone in your production VPC, and was that a decision or a default?
  • What checks your network code before it reaches a real account: a sandbox apply, an emulator, tests, or review alone?

I am not after who is right. I want the pluses and minuses of the columns above to be visible to everyone who reads this, in words from real networks, and the comments are where that happens: https://www.linkedin.com/in/mirac-can-yilmaz

Summary

  • A VPC is a regional private range; a subnet is a slice of it in one zone; a route table decides whether that subnet is public (default route to the internet gateway), private (to a NAT gateway) or isolated (no default route).
  • Plan the CIDR once: no overlap with anything you will connect to, five reserved addresses per subnet, large private subnets for pods, room left over.
  • A NAT gateway is zonal. One per zone keeps a failure in its zone and costs three hourly charges; a single one is cheaper and shares its fate, and its zone boundary, with everyone.
  • Security groups are stateful and reference each other; NACLs are stateless and need the return path. Gateway endpoints for S3 and DynamoDB keep that traffic off the NAT gateway.
  • The API accepts a "private" subnet with a route to the internet gateway. A mocked terraform test and a describe-* script both caught it; the apply did not.
  • A local emulator checks API shape and intent. It accepted a /29, a route to a deleted NAT gateway and a peering between identical ranges. It does not route packets.

Next in the series

This is post 10 of Core Skills. Previous: What Is AWS Emulator?. Next: What Are Cloud Native Buildpacks?, Docker images without a Dockerfile and a base image swapped without a rebuild. Connecting VPCs with Transit Gateway comes later in the series.

The code for this lab (the VPC module, both terraform test files, the verification script, the three bugged variants and the scripts for all seven phases) is shared with Lab Access members on Buy Me a Coffee; the repo invite comes by email after you join: https://buymeacoffee.com/miraccanyilmaz/membership

About the author

Mirac Can Yılmaz

Mirac Can Yılmaz DevOps & Platform Engineer

I work as a DevOps and platform engineer with Kubernetes, GitOps (Argo CD), CI/CD and Terraform. Every post here was tried and measured in my own lab, on kind and Talos clusters: the commands, the errors and the numbers as they happened. The lab code is shared with Lab Access members on Buy Me a Coffee.

İnsanın en büyük hatalarından biri de doğru zamanı yanlış kişilerle doldurmaktır.
Charles Bukowski