Ravindra BagaleCourses & study guides मराठी Track your progress

AWS Cloud

AWS CLI VPC Commands: Create a VPC, Subnets and Route Tables

We build a full VPC from the terminal: VPC, public and private subnets, internet gateway, route tables, security groups and a NAT gateway. Then we tear it down.

In this chapter

  • Create a VPC and subnets
  • Attach an internet gateway and routes
  • Security groups and NACL basics
  • NAT gateway for private subnets
  • Describe and delete in order

1. The big picture: a network by commands

A housing society has one gate (internet gateway), roads (route tables), wings (subnets) and guards at each flat door (security groups).

All VPC commands are inside aws ec2: create-vpc, create-subnet, create-internet-gateway, create-route-table, create-route, create-nat-gateway.

Build ordercreate-vpc 10.0.0.0/16create-subnet public+ privatecreate-internet-gatewayattach-internet-gatewayroute table: 0.0.0.0/0 → igwNAT gateway for private
Delete in the reverse order.

2. Create the VPC and subnets

Use the actual address ranges in the lab. The VPC’s 10.0.0.0/16 is the address envelope for this private training network. The example 10.0.1.0/24 is a smaller subnet inside that envelope. A second subnet must use a different nonoverlapping range. CIDR is the slash notation that describes those network blocks. The VPC addressing chapter walks through how to read it.

As you run the commands, save the VPC ID and the separate public and private subnet IDs. On the route-table checks, compare each association with its subnet ID. Turning on public IP assignment only affects addressing for new network interfaces at launch under the relevant settings. You still need the subnet’s intended route. In cleanup, these saved IDs also help avoid removing a similarly named network from another exercise.

A VPC is your private network. Subnets split it by zone and by public/private.

The VPC gets a CIDR like 10.0.0.0/16. Each subnet takes a smaller CIDR in one Availability Zone.

  1. Create the VPC.
VPC=$(aws ec2 create-vpc --cidr-block 10.0.0.0/16 --tag-specifications "ResourceType=vpc,Tags=[{Key=Name,Value=cli-vpc}]" --query Vpc.VpcId --output text)
echo $VPC

Expected output:

vpc-0a1b2c3d4e5f60718
  1. Turn on DNS hostnames.
aws ec2 modify-vpc-attribute --vpc-id $VPC --enable-dns-hostnames

Expected output:

(no output means success)
  1. Public subnet in ap-south-1a.
PUB=$(aws ec2 create-subnet --vpc-id $VPC --cidr-block 10.0.1.0/24 --availability-zone ap-south-1a --query Subnet.SubnetId --output text)
aws ec2 modify-subnet-attribute --subnet-id $PUB --map-public-ip-on-launch

Expected output:

subnet-0pub...
  1. Private subnet in ap-south-1b.
PRI=$(aws ec2 create-subnet --vpc-id $VPC --cidr-block 10.0.2.0/24 --availability-zone ap-south-1b --query Subnet.SubnetId --output text)

Expected output:

(no output means success)
  1. Verify.
aws ec2 describe-subnets --filters Name=vpc-id,Values=$VPC --query "Subnets[].[SubnetId,CidrBlock,AvailabilityZone,MapPublicIpOnLaunch]" --output table

Expected output:

| subnet-0pub... | 10.0.1.0/24 | ap-south-1a | True  |
| subnet-0pri... | 10.0.2.0/24 | ap-south-1b | False |

3. Internet gateway and public route

Trace one address outside your VPC. The subnet’s associated route table selects a target based on the destination. A default IPv4 route uses 0.0.0.0/0 for destinations that have no more specific matching route. In the public subnet, that route leads to the internet gateway. For direct public IPv4 connectivity, the instance also needs a public IPv4 address and suitable network rules.

A private instance can send outbound internet traffic through the NAT gateway when its route leads there, the NAT is reachable and its own public route reaches the internet gateway. Check the subnet association, destination and route target before blaming the firewall. The existing VPC local route connects VPC addresses without going through an internet gateway.

Without a gateway and a route, nothing in the VPC can reach the internet.

A subnet is public only when its route table sends 0.0.0.0/0 to an internet gateway.

  1. Create and attach the IGW.
IGW=$(aws ec2 create-internet-gateway --query InternetGateway.InternetGatewayId --output text)
aws ec2 attach-internet-gateway --vpc-id $VPC --internet-gateway-id $IGW

Expected output:

igw-0abc...
  1. Public route table.
RT=$(aws ec2 create-route-table --vpc-id $VPC --query RouteTable.RouteTableId --output text)
aws ec2 create-route --route-table-id $RT --destination-cidr-block 0.0.0.0/0 --gateway-id $IGW
aws ec2 associate-route-table --route-table-id $RT --subnet-id $PUB

Expected output:

{ "Return": true }
{ "AssociationId": "rtbassoc-0abc..." }
  1. Verify routes.
aws ec2 describe-route-tables --route-table-ids $RT --query "RouteTables[0].Routes[].[DestinationCidrBlock,GatewayId]" --output text

Expected output:

10.0.0.0/16  local
0.0.0.0/0    igw-0abc...

4. Security groups and NACLs

Guards decide who may knock on each server.

Security groups are stateful and attach to instances. NACLs are stateless and attach to subnets.

  1. Web SG allowing HTTP.
WSG=$(aws ec2 create-security-group --vpc-id $VPC --group-name cli-web --description web --query GroupId --output text)
aws ec2 authorize-security-group-ingress --group-id $WSG --protocol tcp --port 80 --cidr 0.0.0.0/0

Expected output:

(no output means success)
  1. DB SG allowing 3306 only from the web SG.
DSG=$(aws ec2 create-security-group --vpc-id $VPC --group-name cli-db --description db --query GroupId --output text)
aws ec2 authorize-security-group-ingress --group-id $DSG --protocol tcp --port 3306 --source-group $WSG

Expected output:

(no output means success)
  1. See the default NACL.
aws ec2 describe-network-acls --filters Name=vpc-id,Values=$VPC --query "NetworkAcls[0].Entries[].[RuleNumber,Egress,RuleAction]" --output text

Expected output:

100  False  allow
32767 False deny
100  True   allow
32767 True  deny

5. NAT gateway for the private subnet

Private servers need updates from the internet but must not be reachable from it.

A NAT gateway sits in the public subnet with an Elastic IP. The private route table sends 0.0.0.0/0 to it. It costs money per hour.

  1. Create NAT.
EIP=$(aws ec2 allocate-address --query AllocationId --output text)
NAT=$(aws ec2 create-nat-gateway --subnet-id $PUB --allocation-id $EIP --query NatGateway.NatGatewayId --output text)
aws ec2 wait nat-gateway-available --nat-gateway-ids $NAT && echo nat-ready

Expected output:

nat-ready
  1. Private route.
PRT=$(aws ec2 create-route-table --vpc-id $VPC --query RouteTable.RouteTableId --output text)
aws ec2 create-route --route-table-id $PRT --destination-cidr-block 0.0.0.0/0 --nat-gateway-id $NAT
aws ec2 associate-route-table --route-table-id $PRT --subnet-id $PRI

Expected output:

{ "Return": true }
  1. Verify.
aws ec2 describe-nat-gateways --nat-gateway-ids $NAT --query "NatGateways[0].State" --output text

Expected output:

available

6. Same action in Python, Node.js, Java, Go, .NET and PHP

Scripts start in the CLI. Apps call the same API through an SDK. Knowing both helps you move a tested command into real code.

Low-level CLI commands expose service operations. A high-level command or an automatically paginated list can make multiple requests. For example, aws ec2 create-vpc --cidr-block 10.0.0.0/16 maps to the CreateVpc API.

Same action (CreateVpc) from code. Set the intended profile and Region for the SDK. Provider support and precedence can differ by SDK, and an explicit client setting can override defaults.

StackCode
Python (boto3)boto3.client("ec2").create_vpc(CidrBlock="10.0.0.0/16")["Vpc"]["VpcId"]
Node.js (v3)await ec2.send(new CreateVpcCommand({CidrBlock:"10.0.0.0/16"}));
Java (v2)ec2.createVpc(r -> r.cidrBlock("10.0.0.0/16")).vpc().vpcId();
Go (v2)c.CreateVpc(ctx, &ec2.CreateVpcInput{CidrBlock: aws.String("10.0.0.0/16")})
.NETawait ec2.CreateVpcAsync(new CreateVpcRequest{CidrBlock="10.0.0.0/16"});
PHP$ec2->createVpc(["CidrBlock"=>"10.0.0.0/16"]);

7. Clean up so nothing keeps costing

Lab resources left running cost money and can be a security risk.

Delete in reverse order: children first, then parents.

  1. NAT first, then EIP.
aws ec2 delete-nat-gateway --nat-gateway-id $NAT
aws ec2 wait nat-gateway-deleted --nat-gateway-ids $NAT
aws ec2 release-address --allocation-id $EIP

Expected output:

(no output means success)
  1. Security groups.
aws ec2 delete-security-group --group-id $DSG
aws ec2 delete-security-group --group-id $WSG

Expected output:

(no output means success)
  1. Route tables (disassociate first).
for A in $(aws ec2 describe-route-tables --route-table-ids $RT $PRT --query "RouteTables[].Associations[].RouteTableAssociationId" --output text); do aws ec2 disassociate-route-table --association-id $A; done
aws ec2 delete-route-table --route-table-id $RT
aws ec2 delete-route-table --route-table-id $PRT

Expected output:

(no output means success)
  1. IGW, subnets, VPC.
aws ec2 detach-internet-gateway --vpc-id $VPC --internet-gateway-id $IGW
aws ec2 delete-internet-gateway --internet-gateway-id $IGW
aws ec2 delete-subnet --subnet-id $PUB
aws ec2 delete-subnet --subnet-id $PRI
aws ec2 delete-vpc --vpc-id $VPC

Expected output:

(no output means success)
  1. Verify.
aws ec2 describe-vpcs --vpc-ids $VPC

Expected output:

An error occurred (InvalidVpcID.NotFound) ...

Ravindra Bagale's Tip

If delete-vpc fails with DependencyViolation, list network interfaces in the VPC. Something (NAT, endpoint, Lambda) still uses it.

Common errors: cause and safe next check

A route exists but the intended subnet still uses another path

A route table affects a subnet through its association. Inspect the association of the intended subnet as well as the destination and target. Creating a correct-looking table is not proof that this subnet uses it.

A NAT gateway is available but private outbound access still fails

Available describes the gateway state, not the whole path. For the public-NAT internet design, check the private subnet route to that NAT and the NAT’s public-subnet route to the internet gateway. Inspect the existing design before changing security controls.

Someone tries to SSH inward through the NAT Elastic IP

A public NAT gateway supports connections initiated from inside the VPC; it is not an inbound jump host. An SSH timeout through that address is not a reason to expose the private instance. Use the organization’s separately approved private-access method.

Practical questions and full answers

Does naming a subnet public change its route table?

No. A name tag is a label. Inspect the actual subnet association and route target to understand the network path. A label is useful for people, but it does not create or attach a route.

Why check both sides of the public NAT path?

The private subnet must reach the NAT, and the NAT needs its route toward the internet gateway for internet-bound traffic. Checking only one table can miss a broken next hop. The NAT’s available state alone does not validate both routes.

Does a NAT gateway make every private application reachable from the internet?

No. NAT translates outbound connections and their replies; it does not accept unsolicited inbound connections for private instances. Keep that purpose separate from public load balancing or an approved administrative access path.

8. Interview questions and answers

Q. What makes a subnet public?

A route of 0.0.0.0/0 to an internet gateway in its route table.

Q. Where does a NAT gateway live?

In a public subnet, with an Elastic IP.

Q. SG vs NACL?

SG is stateful at the instance. NACL is stateless at the subnet with numbered rules.

Q. How do you allow DB traffic only from web servers?

--source-group with the web security group ID.

Q. Why does delete-vpc fail?

Dependencies remain: ENIs, NAT, IGW, subnets or SGs.

Try at home

  1. Build the VPC, launch an instance in the public subnet and curl it.
  2. Write the cleanup as one bash script and run it.

In short

  1. create-vpc, create-subnet.
  2. IGW + 0.0.0.0/0 route = public.
  3. SG by instance, NACL by subnet.
  4. NAT for private egress.
  5. Delete in reverse order.

Map the route table before testing the connection

Use one disposable VPC, label each subnet and route table, and check the explicit subnet associations. A route to an internet gateway is only part of public IPv4 connectivity; the interface needs a public address and appropriate security rules.

Interview check How do you know the subnet uses your route table?

Describe its explicit associations or identify the VPC's main table when there is no explicit association. Creating a table alone does not attach the subnet.

Reference documentation

Practise this chapter

Interview questions and answers

A private instance cannot download package updates. How do you trace the route?

I would check which route table the private subnet actually uses, then look for its default route to the NAT gateway. I would check the NAT subnet’s route toward the internet gateway and relevant network controls. I would keep the workload private while testing that intended outbound path.

Check your understanding

Choose an answer, then compare your reasoning with the explanation.

0 of 3 answered correctly
1. What tells a subnet where packets to an external address should go?

Answer and explanation

A. Its associated route table

The route table matches the destination and selects a target.

2. A public subnet has an internet gateway route. What else does its instance generally need for direct IPv4 internet access?

Answer and explanation

C. A public IPv4 address and permitted network traffic

The route is only part of the path. The instance needs valid addressing and rules allowing the traffic.

3. What does a NAT gateway route let private instances do in this pattern?

Answer and explanation

B. Initiate outbound internet connections without direct public IPv4 addresses

The private default route can go to NAT for outbound access, while direct inbound addressing remains separate.

Practice Tasks

Practice checks run in your browser. They check the answer for this exercise; they do not create resources or connect to your AWS account.

About this scenario

Pune Fintech Labs is a finance business in Pune. Rohan Kulkarni looks after its IT and cloud work. They count money in INR and run their AWS resources in the ap-south-1 Region. In the tasks below you do real jobs for them using what this lesson teaches. All names, account IDs, IP addresses and numbers are made up for practice.

0 / 12

Easy How many addresses in a /16?

Picking a VPC size needs this count.

Pune Fintech Labs plans the VPC 10.42.0.0/16. How many IP addresses does it hold in total?

  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Easy Create a VPC

A VPC is your own private network in AWS. Everything else lives inside it.

Create a VPC with the CIDR block 10.8.0.0/16.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Easy Create an internet gateway

Without an internet gateway, nothing in the VPC can reach the internet.

Create a new internet gateway.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Medium Create a subnet in one AZ

Subnets split the VPC range and each one lives in exactly one AZ.

In vpc-042045ff53deadbee, create subnet 10.8.1.0/24 in ap-south-1a.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Medium Find the VPC router address

AWS reserves base+1 for the router.

Which address does AWS reserve for the VPC router in subnet 10.42.4.0/24?

  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Medium Usable IPs in an AWS /24 subnet

AWS keeps 5 addresses in every subnet.

How many addresses can Pune Fintech Labs use for servers in subnet 10.42.1.0/24 on AWS?

  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Medium Add the internet route

A subnet is "public" only when its route table sends 0.0.0.0/0 to an internet gateway.

In route table rtb-00542045cc53bb22, send all internet traffic (0.0.0.0/0) to igw-0542045cc53aa11.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Medium Link a subnet to a route table

Until you associate it, a subnet uses the main route table.

Associate subnet subnet-00542045cc53bb1 with route table rtb-00542045cc53bb22.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Medium Attach the internet gateway

A gateway does nothing until it is attached to a VPC.

Attach igw-0542045cc53aa11 to vpc-042045ff53deadbee.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Medium First usable IP for a server

The first 4 addresses are reserved by AWS.

What is the first IP address a server can get in 10.42.20.0/24 on AWS?

  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Hard Pick the smallest prefix

Right-sizing saves address space.

A subnet must hold 100 servers on AWS. What is the largest prefix number (smallest subnet) that fits? Answer like /25.

  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Hard Split a /24 into two

Public and private subnets often split one block.

Split 10.42.8.0/24 into two equal subnets. Write both CIDRs separated by a comma.

  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Revision, comparison and interview cards

Revise this lesson in a few minutes. Save the cards on your phone or download them as PNG files. The QR code on each card opens this lesson.

Build a VPC by commands. Click-built networks are hard to repeat. create-vpc, create-subnet, IGW, route table, route. Public = route 0.0.0.0/0 to the internet gateway. Verify routes with describe-route-tables.
Revision card: Build a VPC by commands · Download PNG · Open card page
NAT and clean up. Private servers need updates but no inbound internet. NAT gateway in a public subnet with an Elastic IP. Private route 0.0.0.0/0 → NAT. Wait nat-gateway-available. Delete in reverse: NAT, EIP, SG, routes, IGW, subnets, VPC.
Revision card: NAT and clean up · Download PNG · Open card page
Security group vs Network ACL. Instance level, stateful. / Subnet level, stateless.
Comparison: Security group vs Network ACL · Download PNG · Open card page
Why does delete-vpc fail?. Something still lives in it: ENI, NAT, IGW, subnet or SG. Error is DependencyViolation. Delete children first, VPC last.
Interview card: Why does delete-vpc fail? · Download PNG · Open card page

More cards: Ravi Sir's Cards.