You are on page 1of 2

AWS VPC Using AWS CLI

CLI command to create a VPC with 10.0.0.0/16 CIDR block


#aws ec2 create-vpc --cidr-block 10.0.0.0/16
output returns with your VPC ID

Create subnet with 10.0.0.0/24 CIDR block using VPC ID from the previous step
#aws ec2 create-subnet --vpc-id $VpcId --cidr-block 10.0.0.0/24
Output returns a SubnetId

To create an Internet gateway


#aws ec2 create-internet-gateway
output returns with your InternetGatwayId

Attach Internet gateway to your VPC using InternetGatewayId


#aws ec2 attach-internet-gateway --vpc-id $VpcId --internet-gateway-id
$InternetgatewayId

Creating Security Group Using CLI


Create a key pair to connect to your instance
#aws ec2 create-key-pair --key-name $KeyPair --query 'KeyMaterial' --output text >
KeyPair.pem
The command pipes your private key directly into KeyPair file with .pem extension

Before launching an instance, you are required to create a security group in your
VPC

#aws ec2 create-security-group --group-name $GroupName --description "" --vpc-id


VpcId
The output returns with a GroupId

Adding a rule that allows SSH access from anywhere with the GroupId
#aws ec2 authorize-security-group-ingress --group-id $GroupId --protocol tcp --port
22 --cidr 0.0.0.0/0

Launch an instance with ImageId into your subnet using GroupId, KeyPair, and
SubnetId.
#aws ec2 run-instances --image-id $ImageId --count 1 --instance-type t2.micro
--key-name $KeyPair --security-group-ids $GroupId --subnet-id $SubnetId
Output returns an InstanceId

Ensure your instance is launched with the InstanceId.

#aws ec2 describe-instances --instance-id $InstanceId


Output returns a PublicIpAddress, through which you can connect to the instance.

Connecting it using the SSH client on a Linux machine

#ssh -i "KeyPair.pem" ec2-user@PublicIpAddress

Clean Up the Resources Using CLI


To delete the Security Group
#aws ec2 delete-security-group --group-id $GroupId
To delete the Subnet
#aws ec2 delete-subnet --subnet-id $SubnetId
To detach the internet gateway from the VPC
#aws ec2 detach-internet-gateway --internet-gateway-id $InternetGatewayId --vpc-id
$VpcId
To delete the internet gateway
#aws ec2 delete-internet-gateway --internet-gateway-id $InternetgatewayId
To delete the VPC
#aws ec2 delete-vpc --vpc-id $VpcId

You might also like