Skip to main content

In this article we will learn how to automate the creation of an Elastic Compute Cloud (EC2) instance on Amazon Web Services (AWS). For this tutorial, I will be using Ubuntu in the Windows Subsystem for Linux (WSL) on Windows 10. We will begin by installing pip, Python’s standard package manager, the AWS Command Line Interface (CLI) & the Boto3 Python library. We will then proceed to creating a user in the Identity and Access Management (IAM) console in which we can interface with AWS programmatically.

Installing the dependencies

Let’s get straight into it. First, let’s open our WSL CLI and check we have python installed by typing python3 --version into the console. You should get a response like below.

Now let’s install pip, Python’s standard package manager, along with the AWS CLI. Enter sudo apt update to update your package list, then enter sudo apt install python3-pip awscli. Wait for pip and the AWS CLI to install then we can move onto the next step.

Once pip is installed, we’re going to install the Boto3 library, which we will be using to interface with AWS. Enter pip install boto3 to your CLI. This will also install the additional dependencies, so don’t be alarmed with the extra installs!

Creating a user with programmatic access in the IAM Console

We now have all our requirements installed, so let’s move on. Log into the AWS console and visit the IAM Console by searching IAM in the search bar.

Under the Access Management heading on the left side menu, select Users and then press the Add User button.

Enter a username and tick “Access Key – Programmatic Access”, then click Next.

We are now met with the permissions page. Select “Attach existing policies directly” and search for AmazonEC2FullAccess. Select the check box beside this policy and click Next.

On this next page, we have the option of creating tags which we can use for storing user information or tracking & controlling access. As this is a beginner tutorial, we will not worry about this and click next without creating one. Review the user you have created, and if you are happy then click Create User.

We are now met with our account details. This screen is only shown once, so it’s best to save these details in a secure location using the “Download .csv” button.

Setting up the AWS CLI

Now let’s go back to our Ubuntu console. We need to insert these new details to the AWS CLI in order for us to create the EC2 instance. We can do this by typing aws configure into the console and entering our Access Key ID and Secret Access Key. For the region, I will set the default to eu-west-1 which is my local region, Ireland, and the Default output format to json.

Now our credentials have been stored, let’s test them. Run the following command and it should return details of any running EC2 instances in JSON format.

aws ec2 describe-instances

Creating a Key Pair for the EC2 Instance

Before we can go ahead and create our EC2 instance, we must create a key pair, which will be used for authentication to SSH into the Virtual Machine at a later stage. Let’s run the below code, which is commented so you can understand what is happening.

import boto3,os

ec2 = boto3.resource('ec2')

keypairfile = open('ec2keypair.pem','w') # create new key pair file
keypair = ec2.create_key_pair(KeyName='ec2keypair') # generate key pair
newkeypair = str(keypair.key_material) # store key pair in variable
keypairfile.write(newkeypair) # save new key pair to file
os.chmod('ec2keypair.pem',400) # change permissions of key pair to 400 (read only)

Creating a new EC2 Instance

We now need to select an Amazon Machine Image in which to create this EC2 Instance. For this tutorial, I have selected the Free tier eligible Amazon Linux 2 AMI (HVM) – Kernel 5.10, SSD Volume Type (x86). The Image ID is what we need for this machine, so in the example it is ami-0bf84c42e04519c85.

Once we have the Image ID, we need to create this new EC2 instance. This is quite straight forward, and can be done in a few lines of Python, thanks to the Boto3 library.

import boto3
ec2 = boto3.resource('ec2')
instance = ec2.create_instances(
     ImageId='ami-0bf84c42e04519c85',
     MinCount=1,
     MaxCount=1,
     InstanceType='t2.nano',
     KeyName='ec2keypair'
 )

In the above code:

  • ImageId is the AMI Image ID from above.
  • MinCount & MaxCount define the amount of instanced launched. In our case, we only want 1 instance – but if we set MinCount to 1 and MaxCount to 4, it would launch 4 instances.
  • InstanceType is the size of the instance, in our case we are using t2.nano as this is in the free tier.
  • KeyName is the name of the key pair we previously created.

As you can see above, our ec2 instance has now been created. We can verify this by going to the EC2 Dashboard in the AWS console.

Wrapping Up

To wrap up, in this tutorial we installed pip, Python’s package manager, the AWS CLI, and the Boto3 python library. We then created a user in the IAM dashboard and applied a policy in order to be able to programmatically create an EC2 instance. We set up the credentials of this user in the AWS CLI and selected our region and output format and then created a key pair, with which we could use to SSH into our EC2 instance. We finally selected an AMI and, using the boto3 python library, created the EC2 instance on AWS and verified that it was created.

Cover photo by Fotis Fotopoulos on Unsplash

close

Don’t miss my posts!

I don’t spam, promise!

Leave a Reply