How to Create Public and Private Subnets in CloudFormation

To create public and private subnets in AWS CloudFormation, you can use the AWS CloudFormation Template Language (CFT) to define your network configuration. Here’s an example CloudFormation template that demonstrates how to create public and private subnets within a Virtual Private Cloud (VPC) in AWS:

Resources:
  MyVPC:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: 10.0.0.0/16
      Tags:
        - Key: Name
          Value: my-vpc

  PublicSubnet:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref MyVPC
      CidrBlock: 10.0.0.0/24
      AvailabilityZone: us-west-2a
      Tags:
        - Key: Name
          Value: public-subnet

  PrivateSubnet:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref MyVPC
      CidrBlock: 10.0.1.0/24
      AvailabilityZone: us-west-2b
      Tags:
        - Key: Name
          Value: private-subnet

In this example, the AWS::EC2::VPC resource creates a VPC with the specified CIDR block. The AWS::EC2::Subnet resources create the public and private subnets within the VPC, using different CIDR blocks and availability zones.

You can save this CloudFormation template in a file with a .yaml or .yml extension. Then, you can use the AWS Management Console, AWS CLI, or AWS SDKs to create a CloudFormation stack from the template. The stack creation process will provision the VPC and subnets according to the template.

Make sure you have the necessary permissions to create VPCs and subnets in your AWS account. You can use the AWS Management Console’s CloudFormation service or the AWS CLI command aws cloudformation create-stack to create the stack from the template.

This example assumes you have already configured the AWS CLI with appropriate credentials and the required permissions for creating VPCs and subnets.