Launching an EC2 Instance Using AWS CLI
By: Elijah Ahianyo
Tags: Aws Cli, Aws Free Tier, Aws Ec2

I am going to assume you already have some insight into the services AWS offers and most importantly, the EC2 instance. If you don't, here's a quick recap/summary:

AWS offers EC2 as a server, more like what you would run in your physical data center.It’ll have access to storage, memory, and a network interface,

and its primary drive will come with a fresh and clean operating system running. Follow this link to learn more about EC2 instances.

Now that we know what EC2 is( did you open the link? No seriously, open it . ill wait).

AWS allows us to launch EC2 instances in regions. You can checkout your region by clicking the right top corner of the console. Follow this link to learn a bit more about AWS regions. AWS offers two ways of launching instances:

using the AWS console

using the AWS CLI(which is why we are here right?)

okay enough talk, let's get right into it.

To launch an instance, we need to follow the following steps which will be treated in detail:

install AWS CLI.

configure AWS CLI.

generate key pair.

create a security group for instance.

create/launch an instance.

Install AWS CLI

Installing the AWS CLI should be a very simple process. The latest version at the time of this writing is 2.0.54. You can check your CLIversion by running this in your terminal:

zeus-of-python@eli:~$ aws --version



This gives the following output:

aws-cli/2.0.54 Python/3.7.3 Linux/4.15.0-118-generic exe/x86_64.ubuntu.18

On Linux, you can install the latest version of the CLI by running the following command.

unzip the package and install.

zeus-of-python@eli:~$ unzip awscliv2.zip

zeus-of-python@eli:~$ sudo ./aws/install

verify installation.

zeus-of-python@eli:~$ aws --version

For Windows and Mac, follow this link to install the CLI.

Configure AWS CLI

Next, we need to configure the CLI to be able to use it. To do this we will need to make sure we have the following:

Access key

secret key

Don’t use your AWS account root user credentials to access AWS, and don’t give your credentials to anyone else. Instead, create individual users for anyone who needs access to your AWS account. Create an IAM user for yourself as well, give that user administrative permissions, and use that IAM user for all your work

AWS recommends using created IAM users other than the root user to access your AWS account or services. To create an access key and secret key, login into your AWS console.

select IAM from services.

select users and create a user as well as group.

click on add user

Enter user name and check the programmatic access box

Enter a group name and select AmazonEC2FullAccess from list

Click on create user

download or store the access and secret key(This is an important step. You won't be able to retrieve this again once you go past this page).

Now, let's configure our CLI. In your terminal, run and follow the prompt .

zeus-of-python@eli:~$ aws configure

AWS Access Key ID [None]: xxxxxxxxxxxxxxxxxx

AWS Secret Access Key [None]: xxxxxxxxxxxxxxxx

Default region name [None]:eu-west-3

Default output format[None]: json

Don't panic if nothing happens after this. In fact, that is a confirmation our configuration worked!

Let's break down what we did up there.

For the access key id and secret key, we entered the generated keys given to us by AWS.

For the default region, we selected the eu-west-3(Paris) region. For a complete list of AWS regions, follow this link.

supported output formats are JSON, table, YAML, YAML stream output, and text. We will stick with JSON for now.

Generate Key Pair

Next, we will generate a key pair to use with our ec2 instances.

A key pair, consisting of a private key and a public key, is a set of security credentials that you use to prove your identity when connecting to an instance

This is basically what we would need to connect to our instance securely over ssh.

To do that, run this in your terminal:

zeus-of-python@eli:~$ aws ec2 create-key-pair --key-name example-user-key --query 'KeyMaterial' --output text > example-user.pem

This will create the example-user.pem file, which contains the ssh private key, in the same directory.

Run the following command to protect against accidental overwriting of the file:

zeus-of-python@eli:~$ chmod 400 example-user.pem

Create a Security Group

Next, we need to create a security group to allow us to access our instance. A security group works much the same way a firewall works. It contains a set of rules that filter traffic coming into and out of an EC2 instance. By default, AWS blocks all traffic coming into an instance. To connect to our instance, we need to create a security group and allow port 22 to allow us to connect to the instance via ssh. To do this, run this in your terminal:

zeus-of-python@eli:~$ aws ec2 create-security-group --group-name example-group --description "security goup for our ec2 instance"



Running the above command returns a JSON containing the group id which we will require later.

{

"GroupId": "sg-0442ea108147ea0c4"

}

To view security groups under EC2 service, run the following in your terminal:

zeus-of-python@eli:~$ aws ec2 describe-security-groups

Next, we will have to allow ssh(port 22) by adding it to the created security group. To do this, run this in your terminal:

zeus-of-python@eli:~$ aws ec2 authorize-security-group-ingress --group-name example-group --protocol tcp --port 22 --cidr 0.0.0.0/0

For the CIDR argument, we want to allow all IP addresses by specifying 0.0.0.0/0 as our IP address range.

Creating Instance

Using an EC2 instance or virtual machine requires an image (more like the operating system to run on it). Amazon provides a variety of AMIs(Amazon Machine Images) for EC2 instances. They provide 4 different types:

Amazon Quick Start AMIs — These type of images are popular choices that appear at the top of the list in your console when you start the process of launching a new instance

AWS Marketplace AMIs — These are official,production-ready images provided and supported by industry vendors like CISCO and Oracle

Community AMIs — These are images created and maintained by independent vendors usually built to meet specific needs

Private AMIs — These are images that are created from your own instance deployments.

In this article, we’re interested in the Amazon Quickstart AMIs. we will be launching a ubuntu 18.04 instance.

To launch our instance, we need the image id of the instance type we want to launch. To get that run this in your terminal:

zeus-of-python@eli:~$ aws ec2 describe-images --owners 099720109477 --filters 'Name=name,Values=ubuntu/images/hvm-ssd/ubuntu-bionic-18.04-amd64-server-????????' 'Name=state,Values=available' --query 'reverse(sort_by(Images, &CreationDate))[:1].ImageId' --output text

This gives the following output :

ami-02d718951aa75291a

Follow the link to get the command for retrieving the image id of the latest AMI for a specific distribution.

Alternatively, you can find an image id by heading to the Ubuntu Amazon EC2 AMI Locator.

Next, let's launch the instance by running the following in the terminal:

zeus-of-python@eli:~$ aws ec2 run-instances --image-id ami-02d718951aa75291a --count 1 --security-group-ids sg-0442ea108147ea0c4 --instance-type t2.micro --key-name example-user-key

Let's break down what is going on.

image-id — The image id of the instance type we want to launch.

count — Number of instances to launch.

security-group-ids — Id of security group we created earlier on.

instance-type — Type of instance we want to run. t2.micro is a free tier instance provided by AWS. This means we won't be charged for using this instance(assuming we are using the 12-month free version). Follow this link to learn more about AWS instance types.

key-name — the name of key-pair we generated earlier on.

This gives an output similar to what is shown below:

...

"Instances": [

{

"AmiLaunchIndex": 0,

"ImageId": "ami-02d718951aa75291a",

"InstanceId": "i-0f2e0a9956f68e3ad",

"InstanceType": "t2.micro",

"KeyName": "example-user-key",

"LaunchTime": "2020-10-08T23:32:10+00:00",

"Monitoring": {

"State": "disabled"

},

"Placement": {

"AvailabilityZone": "eu-west-3b",

"GroupName": "",

"Tenancy": "default"

},

"PrivateDnsName": "ip-172-31-24-130.eu-west-3.compute.internal",

"PrivateIpAddress": "172.31.24.130",

"ProductCodes": [],

"PublicDnsName": "",

"State": {

"Code": 0,

"Name": "pending"

},

...

That's it, we have successfully launched our ec2 instance.

You can list all your instances by running aws ec2 describe-instances in your terminal.

To connect to our instance via ssh, we need to obtain the public IP of our newly created instance. To do this, run this in your terminal:

zeus-of-python@eli:~$ aws ec2 describe-instances --instance-ids i-0f2e0a9956f68e3ad --query 'Reservations[0].Instances[0].PublicIpAddress'

This returns the public IP of the instance:



"35.180.137.149"

Now we can log in .

zeus-of-python@eli:~$ ssh -i example-user.pem ubuntu@35.180.137.149

Welcome to Ubuntu 18.04.5 LTS (GNU/Linux 5.3.0-1035-aws x86_64)

* Management:

* Support: * Documentation: https://help.ubuntu.com * Management: https://landscape.canonical.com * Support: https://ubuntu.com/advantage System information as of Fri Oct 9 12:46:53 UTC 2020 System load: 0.0 Processes: 91

Usage of /: 15.9% of 7.69GB Users logged in: 0

Memory usage: 21% IP address for eth0: 172.31.24.130

Swap usage: 0%

- Reduce system reboots and improve kernel security. Activate at:

https://ubuntu.com/livepatch * Canonical Livepatch is available for installation.- Reduce system reboots and improve kernel security. Activate at: 0 packages can be updated.

0 updates are security updates. The programs included with the Ubuntu system are free software;

the exact distribution terms for each program are described in the

individual files in /usr/share/doc/*/copyright. Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by

applicable law. To run a command as administrator (user "root"), use "sudo <command>".

See "man sudo_root" for details. ubuntu@ip-172-31-24-130:~$

And that is how you launch an instance using the AWS CLI.