Creating a Python 3 Environment on an EC2 Instance with AWS CLI

Helen Campbell
6 min readMay 11, 2021

--

In this project, we will be bootstrapping an EC2 Instance where a Python3 Environment is configured to run a simple application.

An AWS account is needed, along with AWS CLI downloaded on your local system. Provided is a link to guide you through the download process for AWS CLI for different operating systems: https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html

Once you have downloaded and logged into your AWS CLI through your terminal, clear the terminal to create a new space to work on to complete this project.

Step 1: Create an Ubuntu 20.04 EC2 Instance (t2.micro) | Step 2: Connect and login to the instance using your key-pair | Step 3: Refresh updates and upgrade all packages on the instance | Step 4: Create an “environment” directory and a virtual Python environment in “environment” directory | Step 5: Activate virtual environment and confirm environment is up | Step 6: Create a program with a .py file | Step 7: Print your message in that file | Step 8: Exit vim and run the program!

Step 1: Create an Ubuntu 20.04 EC2 Instance (t2.micro)

In Terminal, change the Key Pair Name and Security Group IDs to match your account details using the code below.

This step requires a key pair to exist in your AWS account. It can only be downloaded once to your local environment, so be sure to know where it has been downloaded.

The image ID for an Ubuntu Server 20.04 EC2 is ami-01f87c43e618bf8f0 . The key pair name will be the one you created in your AWS account. The security group can also be found through our VPC dashboard in AWS; I will be using the default security group of my default VPC for this project.

aws ec2 describe-vpcs : this line of command outputs the AWS VPCs in your AWS environment

aws ec2 describe-subnets : this line of command outputs the AWS subnets correlated to your environment. The subnets must match the security group in this project.

aws ec2 describe-security-groups : this line of command outputs the security groups connected to the above VPC. Be sure to match the correct security group to the VPC being worked with.

aws ec2 describe-key-pairs : this line of command outputs the key pairs in your AWS EC2 environment.

aws ec2 run-instances --image-id ami-09e67e426f25ce0d7 --count 1 --instance-type t2.micro --key-name <KEY_PAIR_NAME> --security-group-ids <DEFAULT_SG_ID_NAME> 

You will know your creation has succeeded when the output is a created JSON script. This JSON script validates the creation of the Ubuntu 20.04 EC2 Instance (t2.micro) in your AWS environment. I had to spend about 5 minutes discovering the correct security group to use in my line of code because I have more than a default VPC in my AWS environment. A friendly reminder that there is power in being patient.

Check in the CLI that the creation has been successful using the following code:

aws ec2 describe-instances --filters "Name=instance-type,Values=t2.micro" --query "Reservations[].Instances[].InstanceId"
Proof of newly created EC2

The AWS console is another resource to check the success of the created EC2 Instance.

Step 2: Connect and log in to the Instance using your Key Pair

In the console, select the instance to start a connection. Select the “Connect” button, seen below.

Follow the steps below to SSH into your EC2 Instance through Terminal.

Do not forget to cd downloads (or cd into wherever your private key file was saved). Failing to do so will lead to frustration/confusion because you will get an error about your key pair.

Also, be sure to open port 22 on your security group. If this is not done, you will not be able to connect to your EC2 Instance through CLI.

Be sure that the inbound security group settings have Port 22 open, which is essential when attempting to SSH into the EC2 Instance through the Terminal.

cd Downloads
chmod 400 <KEY_PAIR_NAME>.pem
ssh -I "<KEY_PAIR_NAME>.pem" ubuntu@ec2-<EC2_IP>.compute-
1.amazonaws.com

Success will look like the photo below. You will always be asked yes or no when connecting to the instance, be sure to say yes. Once successfully connected, we turn green and can continue to perform our task in our new instance.

Step 3: Refresh Updates and Upgrade All Packages on the Instance

To update, use the command below:

sudo apt-get update

To upgrade all packages, use the command below:

sudo apt-get upgrade

These updates and upgrades may take longer than expected, be patient as these happen.

Step 4: Create an “environment” Directory and a Virtual Python Environment in the “environment” Directory

mkdir environment 
cd environment
sudo apt install python3-venv
python3 -m venv env

Step 5: Activate Virtual Environment and Confirm Environment is Up

source env/bin/activate
which python

Step 6: Create a program called hello.py

You can create whatever program you’d like; it doesn’t have to be limited to hello.py; feel free to get creative!

vim hello.py

Step 7: Print “What’s Up, World!” in that File

Remember, apostrophes need to be handled appropriately when using Python. Escape characters can be used, or the text can be wrapped with double quotes to use the apostrophe. To start your text, remember to use the “i” key on your keyboard; this enters INSERT mode.

#!/bin/bash print('What\'s Up, World!') #example of using escape character
print("What's Up, World!") #example of wrapping with double quotes

Step 8: Exit vim and Run the Program!

python3 hello.py

Both scripted lines above came out the same, exemplifying how the different handling of apostrophes can create the same output. It all depends on what the user is comfortable doing.

Now that the task is completed, the following steps are to clean up/destroy what we have created.

By typing “exit” on the command line, the connection between the EC2 Instance will be broken. Once that happens, clean up the environment to avoid any unnecessary charges by AWS! This can be done by terminating (through CLI or console) the EC2 Instance created during this project.

aws ec2 terminate-instances --instance-ids <ID_HERE>

One more run of aws ec2 describe-instances can provide you with another check to see that the instance has been terminated. It is always an option to manually check if the instance has been terminated using the AWS Console.

Thanks for trying this exercise with me! I hope you learned something new along the way and enjoyed experimenting with Python scripting. Find me on LinkedIn — linkedin.com/in/helenccampbell

--

--