How to launch EC2 instance using AWS CLI

RUBEL AGRAWAL
3 min readOct 13, 2020

AWS CLI is a command-line interface and it can be downloaded using the below link:

https://awscli.amazonaws.com/AWSCLIV2.msi

Once the download is finished install it.

To check whether the AWS CLI has been successfully installed or not use the below command.

Now to login to AWS using CLI first we need to create an IAM user, create the access key, and attach the policy to the newly created IAM user.

creating IAM user
creating IAM user
creating access key
attaching policy: Administrator Access

Now we have both the secret key and access key which is required to configure AWS CLI.

AWS configure

To launch the EC2 instance we require :

  • AMI which is known as image id
  • instance type
  • subnet id
  • security group
  • key-pair
  • ebs storage (optional)
  • count (no of instances)

We need an image id which we can get from AWS Console

AMI image ids

we can get instance types using the aws ec2 describe-instance-types command

Instance types

now we need a subnet so for that the command is aws ec2 describe-subnets

subnet ids

now Creating Security Group using aws ec2 create-security-group — group-name clisecurity — description “Security group created using cli”

creating a security group “clisecurity”

We require key pair to launch the instance so creating key pair using AWS CLI

aws ec2 create-key-pair — key-name clikey

key-pair creation

Now we are all set to launch EC2 instance

aws ec2 run-instances — image-id ami-09a7bbd08886aafdf — instance-type t2.micro — count 1 — subnet-id subnet-a0646dc8 — security-group-ids sg-01cb51cf6a7ce7db2 — key-name clikey

Instance launch

To create EBS volume using AWS CLI we have to use the given command:

aws ec2 create-volume — volume-type gp2 — availability-zone ap-south-1a — size 2

Note that EBS volume is a zonal service so we need to create the EBS volume in the same availability zone in which our instance has been launched.

EBS volume

As we are having EBS Volume as well as Instance, So now we can attach this newly created EBS volume to our instance by using the given command

aws ec2 attach-volume — volume-id vol-01215af9f37ce5cb7 — instance-id i-0fc2edf5be515f4cf — device /dev/sdf

Attaching EBS volume to the instance

So, this way we can create any number of Ec2 instances as per the requirement.

--

--