Skip to Content
Cloud Engineering Academy
2. AWS Networking & Infrastructure

Public, private and isolated subnets

Build a three-tier subnet layout across two Availability Zones, explain exactly what makes a subnet public, private or isolated, and audit any VPC's subnets with a C# tool.

beginnerโฑ 1 h 10 min๐ŸŸข FreeSAA-C03SOA-C03SCS-C03

Assumes: AWS CLI v2 ยท AWS SDK for .NET v4 (AWSSDK.EC2 4.1.4) ยท .NET 10 LTS ยท CDK v2 (Amazon.CDK.Lib 2.277.0) ยท Terraform AWS provider v6 ยท Region us-east-1. Verified against official sources on 2026-11-18.

Learning objectives

By the end of this lesson you can:

  • State the single rule that makes a subnet "public", and explain why "private" and "isolated" are conventions rather than AWS settings.
  • Decide which tier each Harbourline component belongs in: load balancers, NAT gateways, containers, Lambda functions, databases, VPC endpoints and Transit Gateway attachments.
  • Create six subnets (three tiers ร— two Availability Zones) with the console, CLI, CDK and Terraform, with public IP auto-assignment switched off.
  • Explain the five reserved addresses, AZ names versus AZ IDs, and why you need at least two AZs per tier.
  • Run a C# auditor that classifies every subnet in a VPC by reading its effective route table, and flags risky settings.

Prerequisites

  • Amazon VPC fundamentals โ€” what a VPC, the implied router and an ENI are.
  • CIDR planning โ€” the 10.20.0.0/16 plan with aligned /18 tier blocks used here.
  • Tools: AWS CLI v2 with the learn-sandbox SSO profile, .NET 10 SDK; optionally the CDK CLI and Terraform.

Why this matters in banking

A real-world pattern that auditors find again and again: a team labels a subnet private-db, puts the customer database in it, and moves on. Months later, someone needs the database host to download an agent update, so they add a route from that subnet's route table to a NAT gateway "temporarily". The subnet is still called private-db. Nobody notices that the database tier can now open connections to anywhere on the internet โ€” which is exactly the path an attacker would use to send stolen data out.

The name of a subnet means nothing to AWS. What a subnet can reach is decided only by its route table (and then filtered by security groups and network ACLs). In a bank you must be able to say, for every subnet, "this is what it can reach and here is the evidence". Harbourline's security standard therefore defines three tiers with precise, testable definitions, and its pipeline fails any change that breaks them. This lesson teaches those definitions and gives you the tool that tests them.

For card data, segmentation also has a compliance angle: PCI DSS lets you reduce the scope of an assessment when the cardholder data environment is properly isolated from other networks. Whether a given design achieves that is a question for your QSA (Qualified Security Assessor) and security team โ€” this lesson gives you the building blocks, not a compliance verdict.

The idea in plain language

A subnet is a slice of your VPC's address range that lives in exactly one Availability Zone. Every resource with a network interface โ€” an EC2 instance, an ECS task, a Lambda function attached to a VPC, an RDS database, a load balancer node โ€” gets its private IP address from a subnet.

AWS has no "public" checkbox on a subnet. Instead:

TierDefinition (Harbourline standard)Typical residents
PublicIts route table has a route to an internet gateway (0.0.0.0/0 โ†’ igw-โ€ฆ and/or ::/0 โ†’ igw-โ€ฆ)Internet-facing load balancers, public NAT gateways
PrivateNo route to an internet gateway, but some outbound path beyond the VPC: a NAT gateway, Transit Gateway, egress-only internet gateway or an applianceApplication containers, Lambda functions, internal load balancers
IsolatedOnly the local route (plus, optionally, gateway endpoint routes to S3/DynamoDB). No path out of the VPC at allDatabases, caches, anything holding customer data at rest

Analogy: think of three rooms in a bank branch. The public room is the banking hall: it has a street door, but only the counter staff (load balancers) work there. The private room is the back office: staff can leave through a staff-only exit (the NAT gateway) but nobody can walk in from the street. The isolated room is the vault: it has no exit to the outside at all; the only way in is through the back office, through a door with a keycard reader (security group).

Two consequences surprise most developers:

  1. A subnet can be "public" and still have nothing reachable from the internet. An instance in a public subnet without a public IP address cannot be reached from or reach the internet directly. The route is necessary, not sufficient.
  2. A resource in a "private" subnet can still be exposed โ€” for example through a public load balancer, a misconfigured endpoint service or a reverse proxy. Tiers are one layer of defence, not the whole story.

Subnet facts you must know

FactDetail
AZ-boundA subnet lives in one AZ. A subnet cannot be moved or resized; you delete and recreate it
SizeIPv4 subnets are between /16 and /28
Five reserved addressesIn 10.20.64.0/20: .0 network address, .1 VPC router, .2 Amazon DNS, .3 reserved for future use, and the last address (10.20.79.255) โ€” AWS does not support broadcast, so it is reserved too
Route table associationExactly one route table per subnet. No explicit association โ†’ the VPC's main route table
Network ACL associationExactly one NACL per subnet. No explicit association โ†’ the default NACL
Auto-assign public IPv4MapPublicIpOnLaunch: if on, instances launched here get a public IPv4 address (USD 0.005 per hour each)
Auto-assign IPv6AssignIpv6AddressOnCreation for dual-stack subnets
IPv6-only subnetsPossible for workloads that never need IPv4

AZ names versus AZ IDs

us-east-1a in your account is not necessarily the same physical zone as us-east-1a in another account โ€” AWS maps names to physical zones per account to spread load. The AZ ID (for example use1-az1) is the same everywhere. When several accounts must line up (shared subnets, cross-account PrivateLink, latency-sensitive replicas), plan with AZ IDs. Run aws ec2 describe-availability-zones --query "AvailabilityZones[].[ZoneName,ZoneId]" to see your mapping.

What problem subnets solve

Subnets give you three things:

  • Failure isolation. Because each subnet lives in one AZ, spreading a tier across two or three AZs means a data-centre-level problem takes out one slice, not the whole tier.
  • Routing domains. Each subnet chooses one route table, so you can give the public, private and isolated tiers completely different ways in and out.
  • Coarse filtering. A network ACL attaches at subnet level โ€” useful as a guardrail around a whole tier (security groups vs network ACLs).

Limits and sharp edges (checked 2026-11-18):

ItemDefaultNotes
Subnets per VPC200Adjustable
Route table per subnet1Many subnets can share one route table
Network interfaces per Region5,000, enforced per AZContainers on Fargate and VPC Lambda functions each use ENIs
Usable addressessize โˆ’ 5A /28 has 11 usable; a /24 has 251; a /20 has 4,091

Sharp edges:

  • IP exhaustion is an outage. ECS tasks in awsvpc mode take one IP each; a scale-out event can fail with "insufficient free addresses". Size the app tier generously; you cannot resize a subnet later.
  • Some services demand subnets in at least two AZs โ€” an Application Load Balancer needs at least two, and an RDS DB subnet group must span at least two AZs.
  • Deleting a subnet fails while any ENI exists in it, including ENIs owned by Lambda, load balancers, endpoints or NAT gateways.

Microsoft / Azure comparison

You know (Microsoft/Azure)AWS equivalentWhat's different
VNet subnetVPC subnetAzure subnets span all zones in a region; AWS subnets live in one AZ, so you create one per AZ per tier
"Public" means the VM has a public IP"Public" means the subnet's route table points at an internet gatewayAWS has a gateway object you must attach and route to
Default outbound access (being retired in Azure)None โ€” custom VPC subnets have no internet path by defaultAWS has always been "closed until you open it" for custom VPCs
NSG associated with a subnetNetwork ACL associated with a subnetNACLs are stateless; the stateful filter in AWS is the security group on each ENI
Subnet delegation (e.g. for App Service)No direct equivalent; services just place ENIs in subnets you choosePlan spare addresses for service-owned ENIs
Azure reserves 5 addresses per subnetAWS reserves 5 addresses per subnetSame count, slightly different purposes (.3 is "future use" in AWS)
Availability zones 1, 2, 3 (logical per subscription)AZ names us-east-1a (per account) and AZ IDs use1-az1 (global)Use AZ IDs for cross-account alignment

Architecture

Security-boundary view: the internet trust boundary is the internet gateway, and only the public route table points at it. The app tier is a semi-trusted zone: it can reach AWS services through gateway endpoints and (only if you add a NAT gateway) the internet outbound. The data tier is the most trusted zone: its route table has nothing but local, so even a fully compromised database host has no network path out of the VPC. Security groups then narrow traffic inside the VPC (ALB โ†’ app on 8080, app โ†’ database on 5432), and VPC Flow Logs record what happened.

Step-by-step implementation

Create (or reuse) the VPC

Create hl-m02-vpc with 10.20.0.0/16 and both DNS attributes on, as in VPC fundamentals. Capture its ID in $vpcId.

Create six subnets from the IP plan

Public 10.20.0.0/20 and 10.20.16.0/20, app 10.20.64.0/20 and 10.20.80.0/20, data 10.20.128.0/20 and 10.20.144.0/20 โ€” the first and second AZ of each aligned /18 tier block. Tag each with Tier=public|app|data.

Keep public IP auto-assignment off โ€” everywhere

Even in the public tier. The only things Harbourline puts in public subnets are load balancers and NAT gateways, and AWS assigns their addresses itself. Leaving MapPublicIpOnLaunch off means a developer who launches an instance in the wrong subnet still does not get an internet address.

Create one route table per tier and associate it

hl-m02-public-rt, hl-m02-app-rt and hl-m02-data-rt. Associate each subnet explicitly. Never rely on the main route table; leave it with only the local route so a forgotten subnet ends up isolated, not public. The internet gateway route itself is the subject of route tables and the internet gateway.

Audit the result

Run the C# subnet auditor below. Expect two public, four isolated (the app tier becomes private only once it has a NAT or Transit Gateway route) and no warnings.

AWS Console instructions

  • VPC โ†’ Subnets โ†’ Create subnet. Choose hl-m02-vpc. Add a subnet: name hl-m02-public-us-east-1a, AZ us-east-1a, IPv4 subnet CIDR block 10.20.0.0/20, tags Tier=public, Project=cea-lab, Lab=m02-secure-vpc, Environment=learn, Owner=<you>. Choose Add new subnet for the other five, then Create subnet.
  • Select each public subnet โ†’ Actions โ†’ Edit subnet settings โ†’ make sure Enable auto-assign public IPv4 address is unticked โ†’ Save.
  • VPC โ†’ Route tables โ†’ Create route table three times (hl-m02-public-rt, hl-m02-app-rt, hl-m02-data-rt), VPC hl-m02-vpc.
  • Select a route table โ†’ Subnet associations tab โ†’ Edit subnet associations โ†’ tick the two subnets of that tier โ†’ Save associations.
  • To check a subnet's tier at a glance: VPC โ†’ Subnets โ†’ select a subnet โ†’ Route table tab shows every route that applies to it.
  • VPC โ†’ Your VPCs โ†’ select the VPC โ†’ Resource map draws subnets, route tables and gateways and the links between them โ€” the quickest visual check.

AWS CLI

$p = "--profile", "learn-sandbox", "--region", "us-east-1"
$tags = "{Key=Project,Value=cea-lab},{Key=Lab,Value=m02-secure-vpc},{Key=Environment,Value=learn},{Key=Owner,Value=alex}"

# Find the lab VPC by its Name tag
$vpcId = aws ec2 describe-vpcs --filters Name=tag:Name,Values=hl-m02-vpc @p --query "Vpcs[0].VpcId" --output text

# Three tiers x two AZs, straight from the IP plan
$plan = @(
  @{ Tier = "public"; Az = "us-east-1a"; Cidr = "10.20.0.0/20"   },
  @{ Tier = "public"; Az = "us-east-1b"; Cidr = "10.20.16.0/20"  },
  @{ Tier = "app";    Az = "us-east-1a"; Cidr = "10.20.64.0/20"  },
  @{ Tier = "app";    Az = "us-east-1b"; Cidr = "10.20.80.0/20"  },
  @{ Tier = "data";   Az = "us-east-1a"; Cidr = "10.20.128.0/20" },
  @{ Tier = "data";   Az = "us-east-1b"; Cidr = "10.20.144.0/20" }
)

$subnetIds = @{}
foreach ($s in $plan) {
  $name = "hl-m02-$($s.Tier)-$($s.Az)"
  $id = aws ec2 create-subnet --vpc-id $vpcId --cidr-block $s.Cidr --availability-zone $s.Az @p `
    --tag-specifications "ResourceType=subnet,Tags=[{Key=Name,Value=$name},{Key=Tier,Value=$($s.Tier)},$tags]" `
    --query Subnet.SubnetId --output text
  # Explicitly off, even though it is the default for new subnets in a custom VPC
  aws ec2 modify-subnet-attribute --subnet-id $id --no-map-public-ip-on-launch @p
  $subnetIds[$name] = $id
}

# One route table per tier, explicitly associated
foreach ($tier in "public", "app", "data") {
  $rt = aws ec2 create-route-table --vpc-id $vpcId @p `
    --tag-specifications "ResourceType=route-table,Tags=[{Key=Name,Value=hl-m02-$tier-rt},$tags]" `
    --query RouteTable.RouteTableId --output text
  $subnetIds.Keys | Where-Object { $_ -like "hl-m02-$tier-*" } | ForEach-Object {
    aws ec2 associate-route-table --route-table-id $rt --subnet-id $subnetIds[$_] @p | Out-Null
  }
}

# Show the AZ name -> AZ ID mapping for your account
aws ec2 describe-availability-zones @p --query "AvailabilityZones[].[ZoneName,ZoneId]" --output table

# Show every subnet with its tier, AZ, free addresses and public-IP setting
aws ec2 describe-subnets --filters Name=vpc-id,Values=$vpcId @p `
  --query "Subnets[].[Tags[?Key=='Tier']|[0].Value,AvailabilityZone,CidrBlock,AvailableIpAddressCount,MapPublicIpOnLaunch]" `
  --output table

AvailableIpAddressCount on a fresh /20 shows 4,091 โ€” the 4,096 addresses minus the five AWS reserves. Watch that number in production: alert when the app tier falls below about 20% free.

Infrastructure as Code

ThreeTierVpcStack.cs
using Amazon.CDK;
using Amazon.CDK.AWS.EC2;
using Constructs;

namespace Harbourline.Networking.Examples;

public sealed class ThreeTierVpcStack : Stack
{
    public Vpc Vpc { get; }

    public ThreeTierVpcStack(Construct scope, string id, bool enableNat = false, IStackProps? props = null)
        : base(scope, id, props)
    {
        Vpc = new Vpc(this, "Vpc", new VpcProps
        {
            VpcName = "hl-m02-vpc",
            IpAddresses = IpAddresses.Cidr("10.20.0.0/16"),
            MaxAzs = 2,
            NatGateways = enableNat ? 1 : 0,
            SubnetConfiguration =
            [
                // PUBLIC = route table with 0.0.0.0/0 -> internet gateway. No auto-assigned public IPs.
                new SubnetConfiguration { Name = "public", SubnetType = SubnetType.PUBLIC, CidrMask = 20, MapPublicIpOnLaunch = false },
                new SubnetConfiguration { Name = "public-spare", SubnetType = SubnetType.PUBLIC, CidrMask = 20, Reserved = true },
                // App tier: "private with egress" only when a NAT gateway exists; otherwise isolated.
                new SubnetConfiguration
                {
                    Name = "app",
                    SubnetType = enableNat ? SubnetType.PRIVATE_WITH_EGRESS : SubnetType.PRIVATE_ISOLATED,
                    CidrMask = 20,
                },
                new SubnetConfiguration { Name = "app-spare", SubnetType = SubnetType.PRIVATE_ISOLATED, CidrMask = 20, Reserved = true },
                // Data tier: local route only, always.
                new SubnetConfiguration { Name = "data", SubnetType = SubnetType.PRIVATE_ISOLATED, CidrMask = 20 },
            ],
        });

        Amazon.CDK.Tags.Of(this).Add("Project", "cea-lab");
        Amazon.CDK.Tags.Of(this).Add("Lab", "m02-secure-vpc");
        Amazon.CDK.Tags.Of(this).Add("Environment", "learn");
    }
}

The CDK Vpc construct creates one route table per subnet (not per tier) and wires the internet gateway for you. Reserved = true groups consume address space without creating subnets, which keeps each tier on its aligned /18 block from the CIDR plan. Pick SubnetType by what the tier is allowed to reach โ€” the construct then builds the routes that make it true.

Complete code

A subnet auditor for the platform team. For each subnet in a VPC it finds the effective route table (explicit association or the main one), classifies the subnet by its routes, and warns about risky combinations.

SubnetAudit.csproj
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="AWSSDK.EC2" Version="4.1.4" />
    <PackageReference Include="AWSSDK.SSO" Version="4.1.0.2" />
    <PackageReference Include="AWSSDK.SSOOIDC" Version="4.1.0.2" />
  </ItemGroup>
</Project>
Program.cs
using Amazon;
using Amazon.EC2;
using Amazon.EC2.Model;

// Usage:  $env:AWS_PROFILE = "learn-sandbox"; dotnet run -- vpc-0123456789abcdef0
if (args.Length != 1)
{
    Console.Error.WriteLine("Usage: SubnetAudit <vpc-id>");
    return 2;
}

var vpcId = args[0];
using var ec2 = new AmazonEC2Client(RegionEndpoint.USEast1);
var vpcFilter = new Filter { Name = "vpc-id", Values = [vpcId] };

var subnets = new List<Subnet>();
await foreach (var s in ec2.Paginators.DescribeSubnets(new DescribeSubnetsRequest { Filters = [vpcFilter] }).Subnets)
{
    subnets.Add(s);
}

var routeTables = new List<RouteTable>();
await foreach (var rt in ec2.Paginators.DescribeRouteTables(new DescribeRouteTablesRequest { Filters = [vpcFilter] }).RouteTables)
{
    routeTables.Add(rt);
}

var mainTable = routeTables.SingleOrDefault(rt => (rt.Associations ?? []).Any(a => a.Main == true));
var warnings = 0;

Console.WriteLine($"{"Subnet",-26} {"Name",-30} {"AZ",-12} {"CIDR",-16} {"Free",6}  {"Class",-9} Route table");
foreach (var subnet in subnets.OrderBy(s => s.CidrBlock, StringComparer.Ordinal))
{
    var explicitTable = routeTables.FirstOrDefault(rt => (rt.Associations ?? []).Any(a => a.SubnetId == subnet.SubnetId));
    var table = explicitTable ?? mainTable;
    var routes = table?.Routes ?? [];
    var tier = Classify(routes);
    var name = subnet.Tags?.FirstOrDefault(t => t.Key == "Name")?.Value ?? "(no name)";
    var declaredTier = subnet.Tags?.FirstOrDefault(t => t.Key == "Tier")?.Value;

    Console.WriteLine($"{subnet.SubnetId,-26} {name,-30} {subnet.AvailabilityZone,-12} {subnet.CidrBlock,-16} {subnet.AvailableIpAddressCount,6}  {tier,-9} {table?.RouteTableId}{(explicitTable is null ? " (main)" : "")}");

    var problems = new List<string>();
    if (explicitTable is null) problems.Add("uses the MAIN route table implicitly");
    if (subnet.MapPublicIpOnLaunch == true) problems.Add("auto-assigns public IPv4 addresses");
    if (declaredTier is "data" && tier != "isolated") problems.Add($"tagged Tier=data but is {tier}");
    if (declaredTier is "app" && tier == "public") problems.Add("tagged Tier=app but has an internet gateway route");
    if (routes.Any(r => r.State == RouteState.Blackhole)) problems.Add("has a blackhole route (target deleted)");

    foreach (var problem in problems)
    {
        Console.WriteLine($"    WARNING: {problem}");
    }
    warnings += problems.Count;
}

Console.WriteLine(warnings == 0 ? "No warnings." : $"{warnings} warning(s).");
return warnings == 0 ? 0 : 1;

static string Classify(List<Route> routes)
{
    static bool IsDefault(Route r) => r.DestinationCidrBlock == "0.0.0.0/0" || r.DestinationIpv6CidrBlock == "::/0";

    // Public: a default route whose target is an internet gateway (igw-...). Gateway endpoints use vpce-... targets.
    if (routes.Any(r => IsDefault(r) && r.GatewayId?.StartsWith("igw-", StringComparison.Ordinal) == true))
    {
        return "public";
    }

    // Private: any route that leaves the VPC other than through a gateway endpoint.
    var leavesVpc = routes.Any(r =>
        r.NatGatewayId is not null ||
        r.TransitGatewayId is not null ||
        r.EgressOnlyInternetGatewayId is not null ||
        r.VpcPeeringConnectionId is not null ||
        r.NetworkInterfaceId is not null ||
        r.GatewayId?.StartsWith("vgw-", StringComparison.Ordinal) == true);

    return leavesVpc ? "private" : "isolated";
}

Sample output for the lab VPC before any NAT gateway exists:

Subnet                     Name                           AZ           CIDR               Free  Class     Route table
subnet-0a1โ€ฆ                hl-m02-public-us-east-1a       us-east-1a   10.20.0.0/20       4091  public    rtb-01fโ€ฆ
subnet-0b2โ€ฆ                hl-m02-public-us-east-1b       us-east-1b   10.20.16.0/20      4091  public    rtb-01fโ€ฆ
subnet-0c3โ€ฆ                hl-m02-data-us-east-1a         us-east-1a   10.20.128.0/20     4089  isolated  rtb-07aโ€ฆ
subnet-0d4โ€ฆ                hl-m02-data-us-east-1b         us-east-1b   10.20.144.0/20     4091  isolated  rtb-07aโ€ฆ
subnet-0e5โ€ฆ                hl-m02-app-us-east-1a          us-east-1a   10.20.64.0/20      4087  isolated  rtb-03cโ€ฆ
subnet-0f6โ€ฆ                hl-m02-app-us-east-1b          us-east-1b   10.20.80.0/20      4088  isolated  rtb-03cโ€ฆ
No warnings.

(The ordinal sort puts 10.20.128โ€ฆ before 10.20.64โ€ฆ because it compares text. Sorting by parsed address is a good small exercise.)

Code explained line by line

  1. AWSSDK.EC2 โ€” subnets and route tables are EC2 APIs. AWSSDK.SSO/AWSSDK.SSOOIDC let the SDK use your IAM Identity Center profile.
  2. new Filter { Name = "vpc-id", Values = [vpcId] } โ€” one filter object reused for both describe calls, so you only read this VPC.
  3. ec2.Paginators.DescribeSubnets(...).Subnets โ€” an IAsyncEnumerable that follows NextToken automatically; large VPCs return results in pages.
  4. rt.Associations ?? [] โ€” SDK v4 returns null, not an empty list, for empty collections, so every collection is guarded.
  5. a.Main == true โ€” the main route table is the one with an association flagged Main. Main is a nullable bool? in v4.
  6. explicitTable ?? mainTable โ€” this is exactly how AWS decides: an explicit association wins; otherwise the subnet silently uses the main table. Flagging implicit use is the most valuable check in the tool.
  7. Classify(routes) โ€” implements the three-tier definition. GatewayId holds both internet gateway IDs (igw-) and gateway endpoint IDs (vpce-), so the prefix check matters: a gateway endpoint route does not make a subnet public or private.
  8. r.NetworkInterfaceId is not null โ€” a route to an ENI usually means a firewall or NAT appliance, which is a path out.
  9. declaredTier is "data" && tier != "isolated" โ€” compares what the team says (the Tier tag) with what the routes do. That mismatch is the private-db story from the start of this lesson.
  10. RouteState.Blackhole โ€” a route whose target (for example a deleted NAT gateway) no longer exists; traffic to it is dropped silently.
  11. return warnings == 0 ? 0 : 1; โ€” a non-zero exit code lets a CI job or a scheduled check fail loudly.

Security considerations

  • Define tiers by routes, test them in CI. The CDK assertion tests in the lab (labs/m02-secure-vpc/tests/) check that the data route table has no route other than local. Pair them with this auditor against the live account.
  • Never use the main route table for workloads. Leave it with local only and associate every subnet explicitly. A subnet created by someone in a hurry then lands in the safest tier.
  • Auto-assign public IPv4 off everywhere. Public addresses should come only from deliberate resources (load balancers, NAT gateways, Elastic IPs attached by a reviewed change).
  • Data tier stays isolated. If databases need patches, the managed service (RDS) handles it; if a self-managed host needs packages, use an internal mirror or S3 via a gateway endpoint, not a NAT route.
  • Account-wide backstop. VPC Block Public Access in a workload account means even a wrong route to an internet gateway does nothing (VPC fundamentals).

โš  Learning shortcut โ€” not for production

The lab uses two AZs and /20 subnets everywhere, including the public tier. Production at Harbourline uses three AZs for anything customer-facing, smaller public subnets (load balancers and NAT gateways need few addresses), larger app subnets for container and Lambda ENIs, and often a dedicated small subnet tier for VPC endpoints and Transit Gateway attachments. Subnets are also usually owned by a central network account and shared into workload accounts, so application teams cannot change routes at all โ€” see multi-account network architecture in this module's plan.

Banking use case

Harbourline's Payments Service runs in three tiers in eu-west-2:

TierContentsWhy there
PublicInternet-facing ALB for the mobile-banking API; one NAT gateway per AZOnly these need internet addresses
App (private)ECS Fargate tasks for payment initiation and validation; internal ALB for service-to-service calls; interface endpoints for Secrets Manager, KMS, SQSMust call the sanctions-screening partner over the internet (through NAT) and AWS APIs privately
Data (isolated)Aurora PostgreSQL cluster for payments; ElastiCache for idempotency keysHolds customer and payment data โ€” no path out of the VPC
Attachment (/28 per AZ)Transit Gateway attachment ENIsLink to the on-premises core banking platform; kept apart so routes can be controlled per tier

The architecture review asks one question per tier: "show me the route table". The answer is generated by the auditor and attached to the change record.

Common mistakes

  • Calling a subnet private because of its name โ†’ the route table says otherwise โ†’ classify by routes and alert on tag/route mismatches.
  • Leaving workloads on the main route table โ†’ someone adds an IGW route to "the" route table and every implicit subnet becomes public โ†’ explicit associations only.
  • Putting an instance in a public subnet without a public IP and expecting internet access โ†’ the route exists but the instance has no public address โ†’ use a private subnet and a NAT gateway, or (better) VPC endpoints.
  • One AZ per tier โ†’ an AZ event takes the tier down and some services refuse to deploy โ†’ at least two, ideally three.
  • Subnets sized too small for containers โ†’ Fargate tasks fail to start during a scale-out โ†’ size the app tier for peak tasks plus Lambda ENIs plus headroom.
  • Mixing up AZ names across accounts โ†’ "same AZ" designs land in different physical zones โ†’ use AZ IDs.

Troubleshooting

SymptomLikely causeFix
InvalidSubnet.Range on create-subnetCIDR not inside the VPC's CIDR blocksCheck the plan; add a secondary CIDR if needed
InvalidSubnet.ConflictCIDR overlaps an existing subnetdescribe-subnets and pick the next free aligned block
Instance in public subnet cannot reach internetNo public IPv4/Elastic IP, or SG/NACL blocks outboundDo not fix by adding a public IP โ€” move it to a private subnet with NAT or endpoints
ALB creation fails: "At least two subnets in two different Availability Zones must be specified"Only one public subnet chosenSelect one public subnet per AZ
ECS task stuck in PROVISIONING then fails with an ENI or IP errorApp subnet out of free addressesCheck AvailableIpAddressCount; add subnets (new CIDR blocks) for the tier
DependencyViolation deleting a subnetENIs still present (Lambda, endpoints, load balancers)aws ec2 describe-network-interfaces --filters Name=subnet-id,Values=<id> and remove their owners

Cost and cleanup

Cost: USD 0. Subnets, route tables and their associations are free. Costs only start when you add NAT gateways, public IPv4 addresses, endpoints or load balancers.

If you are continuing to the next lesson, keep the VPC and subnets โ€” it builds on them. Otherwise:

$p = "--profile", "learn-sandbox", "--region", "us-east-1"

# Delete subnets first (they must contain no ENIs)
aws ec2 describe-subnets --filters Name=vpc-id,Values=$vpcId @p --query "Subnets[].SubnetId" --output text |
  ForEach-Object { $_ -split "\s+" } | Where-Object { $_ } |
  ForEach-Object { aws ec2 delete-subnet --subnet-id $_ @p }

# Then the non-main route tables
aws ec2 describe-route-tables --filters Name=vpc-id,Values=$vpcId @p `
  --query "RouteTables[?!(Associations[?Main==``true``])].RouteTableId" --output text |
  ForEach-Object { $_ -split "\s+" } | Where-Object { $_ } |
  ForEach-Object { aws ec2 delete-route-table --route-table-id $_ @p }

# Then the VPC
aws ec2 delete-vpc --vpc-id $vpcId @p

# Nothing tagged for the labs should remain
aws resourcegroupstaggingapi get-resources --tag-filters Key=Project,Values=cea-lab @p --query "ResourceTagMappingList[].ResourceARN"

In the JMESPath filter, the doubled backticks are PowerShell's escape for a literal backtick around true.

Exercises

  • ๐ŸŸข Guided: Create the six subnets and three route tables with the CLI script, run the auditor and confirm all six subnets are isolated (no internet gateway yet) with no warnings. Then remove one explicit association and re-run: you should see the "MAIN route table implicitly" warning.
  • ๐ŸŸก Challenge: Add a fourth tier, endpoints, using /24 subnets carved from the spare 10.20.192.0/18 block, in both AZs, with its own route table. Extend the auditor to print a per-tier summary (subnet count, total free addresses).
  • ๐Ÿ”ด Live problem: A ticket from the database team: "Our Aurora cluster in hl-prod-data-* subnets was flagged by the security scanner as 'internet egress possible', but the subnets are private โ€” please close as false positive." The auditor shows private for those subnets. What do you check, what is the likely cause, and what is your reply?

Assignment

Add tools/subnet-audit/ to your learning repository: the program, a README that defines the three tiers in your own words, and a sample output from your sandbox (account IDs redacted). Bonus: a GitHub Actions workflow that runs it nightly using OIDC federation and fails on warnings.

Solutions

Knowledge check

Interview questions

  • "What makes a subnet public?" โ€” A route to an internet gateway in its route table. I'd add that resources also need a public IP, that I keep auto-assign off, and that I classify subnets by routes, not names.
  • "Where does a NAT gateway go and why?" โ€” A zonal public NAT gateway goes in a public subnet because it needs the IGW route for its own traffic; private subnets route 0.0.0.0/0 to it. (A newer regional NAT gateway mode does not need a public subnet โ€” covered in NAT gateway and egress.)
  • "How do you stop the database tier exfiltrating data?" โ€” Isolated subnets with only the local route, security groups with no unnecessary egress, gateway endpoints with restrictive policies if any AWS access is needed, Flow Logs, and CI tests that fail if a default route appears.
  • "How would you size subnets for Fargate?" โ€” One IP per task, plus ENIs for Lambda, endpoints and load balancers, plus deployment surge (old and new tasks together), plus headroom; /20 or larger per AZ for busy app tiers.

Certification practice

Completion checklist

  • I can define public, private and isolated subnets by their routes
  • I created six subnets across two AZs with auto-assign public IPv4 off
  • Every subnet has an explicit route table association
  • I ran the subnet auditor and understood each column
  • I either kept the VPC for the next lesson or deleted everything and checked for leftover Project=cea-lab resources

Key takeaways

  • "Public" means the subnet's route table points at an internet gateway โ€” nothing else. "Private" and "isolated" are conventions you must define and test.
  • Classify subnets by their effective route table; implicit use of the main route table is a hidden risk.
  • Spread every tier across at least two AZs; AWS subnets never span AZs.
  • Keep public IP auto-assignment off, and keep customer data in isolated subnets with only the local route.
  • Size app subnets for containers and Lambda ENIs; you cannot resize a subnet later.

Further reading

Next: Route tables and the internet gateway.

Independent learning resource โ€” not affiliated with, endorsed or sponsored by Amazon Web Services. AWS and related marks are trademarks of Amazon.com, Inc. or its affiliates. All banking data in examples is fictional. Sample architectures are for learning and are not automatically compliant with GDPR, PCI DSS or any banking regulation.

On this page