Create A Custom VPC and launch an EC2 instance using AWS CLI

Create A Custom VPC and launch an EC2 instance using AWS CLI

Introduction

We will look into the process of launching instances that is through AWS CLI(Command Line Interface). AWS CLI is a tool for running and managing your various AWS services. For Developers, it is a great tool for managing AWS services.

What is VPC?

Amazon Virtual Private Cloud (Amazon VPC) enables you to launch AWS resources into a virtual network that you've defined. This virtual network closely resembles a traditional network that you'd operate in your own data centre, with the benefits of using the scalable infrastructure of AWS.

What is an EC2 instance?

Amazon Elastic Compute Cloud (Amazon EC2) provides scalable computing capacity in the Amazon Web Services (AWS) Cloud. Using Amazon EC2 eliminates your need to invest in hardware up front, so you can develop and deploy applications faster. You can use Amazon EC2 to launch as many or as few virtual servers as you need, configure security and networking, and manage storage. Amazon EC2 enables you to scale up or down to handle changes in requirements or spikes in popularity, reducing your need to forecast traffic.

AWS Configure

'''C:\Users\admin>aws configure

AWS Access Key ID [PSPV]: AKIA**

AWS Secret Access Key [**B9qp]: *

Default region name [us-east-1]: region

Default output format [JSON]:

in command prompt and after executing this we can give the access key id, secret access key, the format of the file, and region these credentials we need to put in that after configuration our command prompt is ready to run another command of AWS CLI.

Creating a VPC

The first thing to do is to create a VPC(virtual private cloud) under which an EC2 instance will be launched. For creating a VPC in CLI type the given command on the cmd.

aws ec2 create-vpc --cidr-block 10.0.0.0/16

Subnet ID generated, so this subnet can be made public later. The CIDR block we have used here is 10.0.1.0/24. Now create a second subnet with CIDR block 10.0.0.0/24.

aws ec2 create-subnet --vpc-id <vpcId> --cidr-block 10.0.0.0/24

Creating Internet Gateway

The Internet gateway is used by the private subnet to access the internet for its updates and other package installations. An internet gateway supports IPv4 and IPv6 traffic. It does not cause availability risks or bandwidth constraints on your network traffic.

aws ec2 create-internet-gateway

After the internet gateway is created, note the InternetGatewayId and to attach this internet gateway to the already created VPC.

aws ec2 attach-internet-gateway --vpc-id <vpcId> --internet-gateway-id <InternetGatewayId>

Note : Here type to noted vpcid(in place of ) and InternetGatewayId(in place of )

Creating Route Table

Next, create a routeing table and assign it to the already created VPC. After creating the routeing table assign the route to this route table.

aws ec2 create-route-table --vpc-id <vpcId>

note the RouteTableID and use it in the next step:

aws ec2 create-route --route-table-id <RouteTableId> --destination-cidr-block 0.0.0.0/0 --gateway-id <nternetGatewayI>

We have used 0.0.0.0/0 as the destination CIDR block.

Viewing the Route Table and Subnets

To check whether route table and subnets are created and assigned successfully use below commands:

aws ec2 describe-route-tables --route-table-id <RouteTableId>
aws ec2 describe-subnets --filters "Name=vpc-id,Values=<vpcId>"  --query "Subnets[*].{​​​​​ID:SubnetId,CIDR:CidrBlock}​​​​​​​​​​​​"

Note : Replace your vpcid in place of .

Associating Route Table and modifying subnet

The next step is to associate the route table with the subnet and make the same subnet as public by mapping the public IP address to it.

aws ec2 associate-route-table --subnet-id <SubnetId> --route-table-id <RouteTableId>

To map the public IP to the subnet

aws ec2 modify-subnet-attribute --subnet-id <SubnetId> --map-public-ip-on-launch

Creating Key Pair and Security Group

The most important step is to create a key pair. This key pair must be kept safe and secure with the user so that the person can access the EC2 instance created using this key pair.

aws ec2 create-key-pair --key-name AWS-Keypair --query "KeyMaterial" --output text > "C:\AWS\AWS_Keypair.pem"

Here we have named the key pair file (.pem file) as AWS-Keypair and the path where our file will be downloaded.

For the Security group use the below commands:

aws ec2 create-security-group --group-name <security-group-name> --description "<description>" --vpc-id <vpcId>

Enter name and description to the security group and add it in place of and . Note GroupId use it in the next step.

aws ec2 authorize-security-group-ingress --group-id <GroupId> --protocol tcp --port 22 --cidr 0.0.0.0/0

Running the EC2 Instance

After the VPC setup is completed sucessfully now the time is to run the instance. For running the EC2 Instance use the command below:

aws ec2 run-instances --image-id <ami-id> --count 1 --instance-type t2.micro 
                      --key-name <Keypair-name> --security-group-ids <SecurityGroupId> 
                      --subnet-id <SubnetId>

At this step, you will need an AMI(Amazon Machine Image) image ID. For this login to your AWS Console and choose any AMI of your type. Copy the image id and replace it here in place of . Also use your key pair name, security group id, and subnet id at the correct place in the above command. Also, make a note of the InstanceId.

Viewing the Instance

Now instance status is "running" type the command to view the complete details of the EC2 instance that you just created.

aws ec2 describe-instances --instance-id <InstanceId>

Verifying the EC2 Instance

To verify whether the EC2 instance created using the AWS CLI is created as per need, log in to your AWS console and open the EC2 service and Check for the instance.

bash script for VPC

#!/bin/bash
# create-aws-vpc#variables used in script:
availabilityZone="ap-south-1"
name="your VPC/network name"
vpcName="$name VPC"
subnetName="$name Subnet"
gatewayName="$name Gateway"
routeTableName="$name Route Table"
securityGroupName="$name Security Group"
vpcCidrBlock="10.0.0.0/16"
subNetCidrBlock="10.0.1.0/24"
port22CidrBlock="0.0.0.0/0"
destinationCidrBlock="0.0.0.0/0"echo "Creating VPC..."#create vpc with cidr block /16
aws_response=$(aws ec2 create-vpc \
 --cidr-block "$vpcCidrBlock" \
 --output json)
vpcId=$(echo -e "$aws_response" |  /usr/bin/jq '.Vpc.VpcId' | tr -d '"')#name the vpc
aws ec2 create-tags \
  --resources "$vpcId" \
  --tags Key=Name,Value="$vpcName"#add dns support
modify_response=$(aws ec2 modify-vpc-attribute \
 --vpc-id "$vpcId" \
 --enable-dns-support "{​​​​\"Value\":true}​​​​​​​​​​​")#add dns hostnames
modify_response=$(aws ec2 modify-vpc-attribute \
  --vpc-id "$vpcId" \
  --enable-dns-hostnames "{​​​​​​​​​​​\"Value\":true}​​​​​​​​​​​")#create internet gateway
gateway_response=$(aws ec2 create-internet-gateway \
 --output json)
gatewayId=$(echo -e "$gateway_response" |  /usr/bin/jq '.InternetGateway.InternetGatewayId' | tr -d '"')#name the internet gateway
aws ec2 create-tags \
  --resources "$gatewayId" \
  --tags Key=Name,Value="$gatewayName"#attach gateway to vpc
attach_response=$(aws ec2 attach-internet-gateway \
 --internet-gateway-id "$gatewayId"  \
 --vpc-id "$vpcId")#create subnet for vpc with /24 cidr block
subnet_response=$(aws ec2 create-subnet \
 --cidr-block "$subNetCidrBlock" \
 --availability-zone "$availabilityZone" \
 --vpc-id "$vpcId" \
 --output json)
subnetId=$(echo -e "$subnet_response" |  /usr/bin/jq '.Subnet.SubnetId' | tr -d '"')#name the subnet
aws ec2 create-tags \
  --resources "$subnetId" \
  --tags Key=Name,Value="$subnetName"#enable public ip on subnet
modify_response=$(aws ec2 modify-subnet-attribute \
 --subnet-id "$subnetId" \
 --map-public-ip-on-launch)#create security group
security_response=$(aws ec2 create-security-group \
 --group-name "$securityGroupName" \
 --description "Private: $securityGroupName" \
 --vpc-id "$vpcId" --output json)
groupId=$(echo -e "$security_response" |  /usr/bin/jq '.GroupId' | tr -d '"')#name the security group
aws ec2 create-tags \
  --resources "$groupId" \
  --tags Key=Name,Value="$securityGroupName"#enable port 22
security_response2=$(aws ec2 authorize-security-group-ingress \
 --group-id "$groupId" \
 --protocol tcp --port 22 \
 --cidr "$port22CidrBlock")#create route table for vpc
route_table_response=$(aws ec2 create-route-table \
 --vpc-id "$vpcId" \
 --output json)
routeTableId=$(echo -e "$route_table_response" |  /usr/bin/jq '.RouteTable.RouteTableId' | tr -d '"')#name the route table
aws ec2 create-tags \
  --resources "$routeTableId" \
  --tags Key=Name,Value="$routeTableName"#add route for the internet gateway
route_response=$(aws ec2 create-route \
 --route-table-id "$routeTableId" \
 --destination-cidr-block "$destinationCidrBlock" \
 --gateway-id "$gatewayId")#add route to subnet
associate_response=$(aws ec2 associate-route-table \
 --subnet-id "$subnetId" \
 --route-table-id "$routeTableId")echo " "
echo "VPC created:"
echo "Use subnet id $subnetId and security group id $groupId"
echo "To create your AWS instances"# end of create-aws-vpc

Did you find this article valuable?

Support Ashu Blog by becoming a sponsor. Any amount is appreciated!