Creating AWS EC2 instances from CLI

Published on Author admin

Install Python PIP:

yum install python-pip

or

yum install python3-pip

Install AWS CLI using PIP:

pip install awscli --user

or

pip3 install awscli --user

PIP installs aws inside $HOME/.local/bin/ directory.
Configure $PATH inside ~/.bash_profile

PATH=$PATH:$HOME/bin:$HOME/.local/bin

Configure AWS client:

$ aws configure
AWS Access Key ID [None]: AWSACCESSKEYID
AWS Secret Access Key [None]: AWSSECRETACCESSKEY
Default region name [None]: us-west-2
Default output format [None]: json

AMI (Amazon Machine Image) number for CentOS 7 image:

ami-18f8df7d

Create new VM using CentOS image:

aws ec2 run-instances --image-id ami-18f8df7d --security-group-ids SG-ID --count 1 --instance-type t2.micro --key-name KEYNAME --query 'Instances[0].InstanceId'

Get IP address of newly created instance:

aws ec2 describe-instances --instance-ids INSTANCE-ID --query 'Reservations[0].Instances[0].PublicIpAddress'

Get IP addresses of all instances:

aws ec2 describe-instances | grep PublicIpAddress
aws ec2 describe-instances | jq .Reservations[].Instances[].NetworkInterfaces[].Association.PublicIp
aws ec2 describe-instances | jq .Reservations[].Instances[].PublicIpAddress

Connect to VM via SSH:

ssh centos@IP_ADDR

Terminate (destroy) instance:

aws ec2 terminate-instances --instance-ids INSTANCE-ID

Get all instances details:

aws ec2 describe-instances

Get all virtual volumes (disks) details:

aws ec2 describe-volumes

Delete volume:

aws ec2 delete-volume --volume-id VOLUME-ID

Terminate ALL instances:

aws ec2 terminate-instances --instance-ids `aws ec2 describe-instances | jq .Reservations[].Instances[].InstanceId | sed 's/"//g'`

List all instances states:

aws ec2 describe-instances | jq .Reservations[].Instances[].State.Name