Wednesday, November 12, 2025

Create VPC and Subnets in AWS CDK (Python) | Explained Step-by-Step 🚀

In this blog, we’ll explore how to create a VPC and subnets using AWS CDK in Python. Whether you’re new to AWS CDK or cloud networking, this post will help you understand how to set up a VPC with public and private subnets, configure CIDR blocks correctly, and understand how AWS handles availability zones.

You can also watch the complete hands-on tutorial on my YouTube channel here:



Understanding the VPC Basics:

A Virtual Private Cloud (VPC) is your private network in AWS. It allows you to control your IP address range, create subnets, and configure route tables and gateways.

When you create a VPC using AWS CDK, you define the following:

  • CIDR Block (e.g., 10.0.0.0/28)

  • Subnets (public/private/isolated)

  • Availability Zones

  • NAT Gateway (if private subnets need internet access)

Setting Up the VPC Using CDK:

Here’s how you can define your VPC in CDK:

from aws_cdk import (
    # Duration,
    Stack,
    aws_ec2 as ec2,
)
from constructs import Construct
import os

class AwsCdkVpcStack(Stack):

    def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        # The code that defines your stack goes here
        self.vpc = ec2.Vpc(
            self,
            id=f"{os.getenv('AWS_ENV')}_{os.getenv('VPC_NAME')}",
            vpc_name=os.getenv('VPC_NAME'),
            cidr=os.getenv('CIDR_BLOCK'),
            max_azs=2,
            create_internet_gateway=True,
            nat_gateways=0,    

            subnet_configuration=[
                ec2.SubnetConfiguration(
                    name=f"PublicSubnet_{os.getenv('AWS_ENV')}_{os.getenv('VPC_NAME')}_{self.region}",
                    subnet_type=ec2.SubnetType.PUBLIC,
                    cidr_mask=28,
                    map_public_ip_on_launch=True
                ),
                ec2.SubnetConfiguration(
                    name=f"PrivateSubnet_{os.getenv('AWS_ENV')}_{os.getenv('VPC_NAME')}_{self.region}",
                    subnet_type=ec2.SubnetType.PRIVATE_WITH_EGRESS,
                    cidr_mask=28
                ),
                ec2.SubnetConfiguration(
                    name=f"IsolatedSubnet_{os.getenv('AWS_ENV')}_{os.getenv('VPC_NAME')}_{self.region}",
                    subnet_type=ec2.SubnetType.PRIVATE_ISOLATED,
                    cidr_mask=28
                ),
            ]
        )




Command Purpose
cdk synth Synthesizes your CDK code into a CloudFormation template
cdk bootstrap Prepares your AWS environment for CDK deployments
cdk deploy Deploys your stack(s) to AWS


GITHUB Link: https://github.com/jksnu/aws_vpc_cdk.git