Using AWS CLI to Launch an EC2 Instance with Apache Webserver

Zaire Ali
8 min readSep 27, 2021

--

Introduction

Recently, Amazon Web Services (AWS) was reported to be the largest provider of cloud infrastructure. Many companies and organizations are utilizing the AWS platform for many of their cloud services. AWS offers a wide variety of solutions such as the Elastic Compute Cloud (EC2). EC2 instances are useful because they can be created, scaled, and deployed programmatically. In this example, we will set up AWS CLI and an EC2 instance using user data. This tutorial assumes you already have an AWS account and an administrator account.

AWS CLI Setup

To gain the full benefit of AWS, we need to learn how to programmatically interact with our account. To do this we use the AWS command-line interface (CLI). To install AWS CLI on your system, head over to the download page at https://aws.amazon.com/cli/ and select your operating system (OS) from the right-hand pane. I am using Windows 10 so I downloaded the 64-bit Windows installer.

Upon successful installation, you can validate AWS CLI is installed properly by using the following command on the command prompt:

aws --version

We will need our Access Key ID and Secret Access Key in order to authenticate using the CLI. When you created your admin IAM user account, you should have copied this information into a secure location. If it wasn’t copied or was misplaced, we can create a new set of keys. Login to the AWS console and navigate to IAM as shown.

All Services -> Security, Identity, & Compliance -> IAM

Under access management on the left-hand pane select users then click your user name. Next, navigate to the security credentials tab. You can have a maximum of two access keys (active or inactive) at a time. If you have two, you will need to delete one first. To proceed, click create access key. Copy down the Access Key ID and Secret Access Key.

Return to the command line and run the following command to configure AWS CLI.

aws configure

This allows you to configure your AWS CLI with your login information. Paste your Access Key ID and Secret Access Key. For the default region, I chose us-east-1 for two reasons. First, I am located on the east coast and second, all AWS features are not available everywhere but us-east-1 has them all and is usually the region new features are tested at. Upon completion, you can validate your configuration by running aws configure again. This will display the current values for each setting as you press enter to iterate through the configurations.

AWS EC2 Authentication

For us to authenticate with our EC2 instance we will be using key pairs. We will use the following command to create a key pair named, MyKeyPair, and output the key contents to a file named MyKeyPair.pem.

aws ec2 create-key-pair --key-name MyKeyPair --key-type rsa --query “KeyMaterial” --output text > MyKeyPair.pem

To validate the key pair exists we can use the command:

aws ec2 describe-key-pairs --key-name MyKeyPair

AWS EC2 Security Group

A security group is used as a firewall to determine what traffic can enter and leave an EC2 instance. For our example, we will need to allow traffic to our internet protocol (IP) address over port 22 which allows secure shell (SSH) access. SSH is typically used to remotely login to a machine using the console. Since I am on a Windows machine, I will also allow traffic over port 3389 which is used for Remote Desktop Protocol (RDP). To begin, we will use the following command to create the security group named, my-sg, with the description, My security group.

aws ec2 create-security-group --group-name my-sg --description “My security group”

Next, we will want to get our public IP address. For this we will run the following command and get an ip address like, 127.0.0.1.

curl https://checkip.amazonaws.com
127.0.0.1

We then want to use the following command to add the tcp port exceptions where 127.0.0.1 is the public IP address we obtained from the curl command.

aws ec2 authorize-security-group-ingress --group-name my-sg --protocol tcp --port 22 --cidr 127.0.0.1/32aws ec2 authorize-security-group-ingress --group-name my-sg --protocol tcp --port 3389 --cidr 127.0.0.1/32

In addition, we also want people to be able to access our webserver over port 80 which is HTTP. To allow all access, we run the following command with 0.0.0.0/0 as the cidr. This specifies, to open this port for the world.

aws ec2 authorize-security-group-ingress --group-name my-sg --protocol tcp --port 80 --cidr 0.0.0.0/0

AWS EC2 Setup

With our key pair and security group created, we are ready to create our EC2 instance. AWS offers a wide range of instance types with varying compute and memory capacity. For our example, we will be using the t3.nano instance since it only costs $0.0052/hr. The list of all available instance types can be found at https://aws.amazon.com/ec2/instance-types/.

To create our EC2 instance, we also need to select an Amazon Machine Image (AMI) for the OS we will be deploying. For this example, we will deploy Ubuntu 20.04 server. We can go to https://console.aws.amazon.com/ec2/v2/home?region=us-east-1#LaunchInstanceWizard to lookup an AMI for Ubuntu 20.04 server. It is possible to use the describe-images command to search for AMIs via the AWS CLI but the web portal explicitly denotes AMIs that are free tier eligible. We scroll down until we see our OS and copy the ImageId for the AMI.

Next, we need to make sure AWS installs Apache on the EC2 instance. We can write a bash script that will be executed when the instance is setup. Windows does not come with a command prompt editor, so we will need to download VIM. To do this, head to vim.org to download and install VIM. Upon successful completion, VIM will be available via command prompt. This can be done using the following command.

vim user-data.sh

Once in the empty file, strike the “I” key to enter insert mode. While in insert mode, you will be able to type the following block of code. This code will first, make sure all of our repositories are up to date and upgrade all of the packages. Next, it will install and start apache2. Finally, it will make sure that apache2 is started on each boot.

#!/bin/bash
apt update -y
apt upgrade -y
apt-get install -y apache2
systemctl start apache2
systemctl enable apache2

To exit insert mode, press the “Esc” key. To save our file and quit VIM, we enter the following command and press “Enter”.

:wq

We now have everything we need to create our EC2 instance. We can use the following command to create our instance with ami-09e67e426f25ce0d7 as our image-id, t3.nano as our instance-type, MyKeyPair as my key pair name, my-sg as my security group name, and user-data.sh as our user data file. Also note that file:// should be placed in front of the user data file name.

aws ec2 run-instances --image-id ami-09e67e426f25ce0d7 --count 1 --instance-type t3.nano --key-name MyKeyPair --security-groups my-sg --user-data file://user-data.sh

Upon completion, we can use the following command to validate the creation of our EC2 instance. The command lists ec2 instances that have the security group my-sg that we created earlier. Please note the InstanceId in the InstanceId field and the IP address in the PublicIpAddress field for later.

aws ec2 describe-instances --filter "Name=instance.group-name,Values='my-sg'"

Validate Apache

It will take a few minutes to completely setup the EC2 instance and run the commands we specified. Before we can validate the Apache installation, the instance needs to be completely initialized. We can run the following command to check on the instance’s status where i-078c570d8107fa6e7 is our instanceId.

aws ec2 describe-instance-status — instance-id i-078c570d8107fa6e7

If the instance is still spinning up, we will get a response like the one shown below. Wait a few minutes and rerun the command.

If the instance has completed initialization, we will receive the following response.

Now that our instance is fully initialized, we should be able to view the default Apache page using a web browser. To do this, we open a web browser and navigate to our EC2 instance using the public IP address we copied earlier. If we see the following page, “It works!”

Wrap Up — Stop EC2 Instance

Finally, AWS charges for EC2 uptime so we want to shut down our EC2 instance when it is not in use. Even though we are using a free tier, this is a good practice to get into. In order to shutdown the instance we will use its InstanceId. To stop the instance, run the following command where i-078c570d8107fa6e7 is the InstanceId.

aws ec2 stop-instances --instance-id i-078c570d8107fa6e7

--

--

Zaire Ali

Machine Learning Engineer by day, self-proclaimed scientist by night. I have fun by leveraging machine learning, Python, AWS, and Terraform.