Creating a custom VPC in AWS - Step-by-Step CLI Walkthrough
AWSTemplateFormatVersion: '2010-09-09' Description: Custom VPC with public and private subnets Resources: MyVPC: Type: AWS::EC2::VPC Properties: CidrBlock: 10.0.0.0/16 EnableDnsSupport: true EnableDnsHostnames: true Tags: - Key: Name Value: my-custom-vpc PublicSubnet: Type: AWS::EC2::Subnet Properties: VpcId: !Ref MyVPC CidrBlock: 10.0.1.0/24 MapPublicIpOnLaunch: true AvailabilityZone: us-east-1a Tags: - Key: Name Value: my-public-subnet PrivateSubnet: Type: AWS::EC2::Subnet Properties: VpcId: !Ref MyVPC CidrBlock: 10.0.2.0/24 MapPublicIpOnLaunch: false AvailabilityZone: us-east-1a Tags: - Key: Name Value: my-private-subnet InternetGateway: Type: AWS::EC2::InternetGateway Properties: Tags: - Key: Name Value: my-internet-gateway AttachGateway: Type: AWS::EC2::VPCGatewayAttachment Properties: VpcId: !Ref MyVPC InternetGatewayId: !Ref InternetGateway PublicRouteTable: Type: AWS::EC2::RouteTable Properties: VpcId: !Ref MyVPC Tags: - Key: Name Value: my-public-route-table PublicRoute: Type: AWS::EC2::Route DependsOn: AttachGateway Properties: RouteTableId: !Ref PublicRouteTable DestinationCidrBlock: 0.0.0.0/0 GatewayId: !Ref InternetGateway PublicSubnetRouteTableAssociation: Type: AWS::EC2::SubnetRouteTableAssociation Properties: SubnetId: !Ref PublicSubnet RouteTableId: !Ref PublicRouteTable
This file creates a custom VPC with a large private IP range (10.0.0.0/16). It defines one public subnet and one private subnet inside the VPC. An Internet Gateway is attached to allow internet access for the public subnet. A route table is created and associated with the public subnet to send internet traffic through the gateway.
MyVPC: The main private network.
PublicSubnet: A subnet that can access the internet.
PrivateSubnet: A subnet isolated from the internet.
InternetGateway: Connects the VPC to the internet.
RouteTable and Route: Directs internet traffic from the public subnet.
aws cloudformation create-stack --stack-name my-custom-vpc-stack --template-body file://vpc.yaml
--stack-name - Names the CloudFormation stack for easy management--template-body - Specifies the local template file to useaws cloudformation describe-stacks --stack-name my-custom-vpc-stack
--stack-name - Specifies which stack to describeaws ec2 describe-vpcs --filters Name=tag:Name,Values=my-custom-vpc
--filters - Filters VPCs by tag nameIf you remember nothing else from this pattern, remember: a custom VPC lets you control your own private network space in the cloud with your own IP ranges and internet access rules.