[AWS](EN) Create, list and delete EC2 instance using AWS CLI

Create, list and delete EC2 instance using AWS CLI


Environment and Prerequisite

  • Ubuntu 18.04
  • AWS CLI
  • Bash shell(/bin/bash)


Process

  1. Install AWS CLI
  2. Basic Setting(Configuration and Credential File Settings)
  3. EC2 Instance Create, List and Delete


Install AWS CLI

Package update and upgrade

sudo apt-get update -y && sudo apt-get upgrade -y

Install pip3

sudo apt-get install python3-pip

Install AWS CLI

  • Logout and login again if aws command is not work.
pip3 install awscli --upgrade --user

Check AWS CLI version

$ aws --version
aws-cli/1.16.310 Python/3.6.9 Linux/4.15.0-72-generic botocore/1.13.46


Basic Setting(Configuration and Credential File Settings)

Before setting

aws configure

$ aws configure
AWS Access Key ID [None]: [YOUR KEY]
AWS Secret Access Key [None]: [YOUR KEY]
Default region name [None]: ap-northeast-2
Default output format [None]: json

Check ~/.aws/credentials setting

$ cat ~/.aws/credentials
[default]
aws_access_key_id = [YOUR KEY]
aws_secret_access_key = [YOUR KEY]

Check ~/.aws/config 설정 확인 setting

$ cat ~/.aws/config
[default]
region = ap-northeast-2
output = json


EC2 Instance Create, List and Delete

Before setting

  • Consider that there is already made EC2 security group
  • You can make security group in aws website. My security group opens only ssh port in inbound and opens all ports in outbound.

Create key pair

  • Store key pair in your computer which is made from below command.
  • You can use your own key pair. However, public key should be in AWS and private key should be kept in your computer.
aws ec2 create-key-pair --key-name TestKeyPair --query 'KeyMaterial' --output text > TestKeyPair.pem

Create EC2 instance

  • --image-id: Instance image ID
  • ami-082bdb3b2d54d5a19: Ubuntu Server 16.04 LTS (HVM), SSD Volume Type
  • --count: Number of instances
  • --key-name: Key pair key
  • TestKeyPair: The key pair that we made above
  • --security-group-ids: Security group ID
aws ec2 run-instances --image-id ami-082bdb3b2d54d5a19 --count 1 --instance-type t2.micro --key-name TestKeyPair --security-group-ids [YOUR SECURITY GROUP ID]

List EC2 instances

  • --filters: It is filter for instances. In this example, it gets instances of which instance-type is t2.micro.
  • --query: It is option for showing results of instances. In this example, it shows only ID of instances.
aws ec2 describe-instances --filters "Name=instance-type,Values=t2.micro" --query "Reservations[].Instances[].InstanceId"

Connect to EC2 instance

  • Set key file permission
chmod 400 TestKeyPair.pem
  • Access to instance using ssh
ssh -i "TestKeyPair.pem" [USER NAME]@[PUBLIC IP or PUBLIC AWS DNS]

Delete EC2 instance

  • --instance-ids: Delete using instance ID
aws ec2 terminate-instances --instance-ids [YOUR INSTANCE ID]


Reference