Provisioning an EC2 instance using Terraform & Keypair

Nyukeit
5 min readNov 22, 2022

--

In this article, we will go through the process of creating an EC2 instance in your AWS account using Terraform and AWSCLI. We will also see how we can connect to the newly created instance using SSH. This article makes use of Ubuntu 22.04 but the commands should work on any linux, with only needing to replace OS specific commands like apt-get.

Prerequisites

  • AWS Account
  • Linux (this article uses Ubuntu 22.04)

Install Terraform

To begin with, we first need to install gnupg and software-properties-common, if not already present.

sudo apt-get update
sudo apt-get install -y gnupg software-properties-common

After installing these, we need to add the HashiCorp GPG Key to the Ubuntu system.

wget -O- https://apt.releases.hashicorp.com/gpg | \
gpg — dearmor | \
sudo tee /usr/share/keyrings/hashicorp-archive-keyring.gpg

Now, let’s go ahead and add the HashiCorp repository to Ubuntu. This repository will allow us to find the Terraform software on the internet.

echo “deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] \
https://apt.releases.hashicorp.com $(lsb_release -cs) main” | \
sudo tee /etc/apt/sources.list.d/hashicorp.list

And finally, it’s time to install Terraform itself.

sudo apt-get update
sudo apt-get install terraform

Wait till the command-line finishes the installation. To verify if Terraform was installed successfully, use this command.

terraform -version

Now that we have successfully installed Terraform on our system, it is time to install AWSCLI, the utility that will help us configure our AWS with credentials.

Install AWSCLI

Although there are a few ways to install AWSCLI, we will use the method prescribed in the official documentation by Amazon.

curl “https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o “awscliv2.zip”
unzip awscliv2.zip
sudo ./aws/install

Once again, we verify the successfull installation of AWSLI by checking its version by typing in the following command.

aws --version

AWS Credentials

We will assume by this point, you have an AWS account created. If not, now is the time to do it. Log in to your AWS account and on the top right corner, click on your profile picture. Go to Security Credentials and create a credential.

Note down the Access Key and Secret key somewhere safe.

Come back to your terminal and type the following command

aws configure

AWS will present you with options to paste/type the following one by one. Press enter after pasting in each line. Note that [none] means there is no data configured for that key yet.

Access Key [none]:
Secret Key [none]:
Region [none]:
Output format [none]:

Now we have our AWSCLI configured to access the AWS account, however, this is not enough to launch an EC2 instance. For that, we need a keypair.

Sidenote: This article makes use of the root account in AWS. You may want/need to use an IAM user with permission policies if required.

Again, we confirm everything is in place by verifying. Seeing is believing.

cd /.aws
cat credentials

EC2 Keypair

In your AWS dashboard, go to EC2. If you can’t find a direct link anywhere, type EC2 in the search box on top.

On the left navigation, go to Keypair. Click on Create.

Give a suitable name to your keypair file and select RSA and PEM and click on Save. This will download the PEM file to your system.

In terminal, create a folder for your project.

mkdir yourprojectname

If you are able to, move the keypair file to your project folder. If not, open the PEM file in a text editor, copy the contents.

In your terminal, navigate to your project folder and type the following commands.

sudo nano mykeyfile.pem

You can replace mykeyfile with any name for the file you want.

Now paste the content of the download pem file into the nano editor and press Ctrl + x + y. This will create the same pem file in your terminal.

We will use this keypair file to ssh into the newly created EC2 Instance.

Creating Terraform Scripts

Now that we have the prerequisites in place, let’s create a Terraform plan and apply it to create our instance.

cd yourprojectname

Once inside your project folder, create your first Terraform file which will contain the same credentials that we used for AWSCLI

sudo nano creds.tf

Inside the nano editor, type/paste the following

provider “aws” {
access_key = “<your aws access key>”
secret_key = “<your aws secret key”
region = “<your aws region>”
}

Save this file by using the combination Ctrl + x + y

Now it’s time to create the main Terraform script that will actually execute the commands to launch our EC2 instance.

sudo nano main.tf
resource “aws_instance” “myproject” {
ami = “ami-2757f631”
instance_type = “t2.micro”
key_name = “mykeyfile”
}

NOTE: AMI is the Amazon Machine Image and the alphanumeric corresponds to a particular image ID. You can search for the AMI that you wish to launch. The instance type must match with the type of your AMI. In the example above, the AMI-2757f631 is an Ubuntu Xenial 16.04 image with the type t2 micro.

We now have the Terraform plan ready and we need to initiate it.

terraform init

Once the configuration is initialized, we need to apply it for Terraform to create our EC2 instance.

terraform apply

When prompted, type yes

Terraform will now begin to create the EC2 instance. Not that this may take up to a minute and a half to finish depending on the image.

To verify the creation of the instance, go to your EC2 dashboard and go to Instance and you should see your instance in the running state.

Connecting to EC2 Instance using SSH

The reason why we initiated our instance using a keypair file was to be able to SSH into it after creation. And we will see how this becomes very easy now.

The first step is to go to your EC2 dashboard and click on Security Groups.

There, select your security group and click on Inbound Rules tab. Click on Edit Inbound Rules

There might be a default rule already added. Leave it as it is.

Click on Add Rule and select the protocol as SSH and source as Custom. Click on the search box next to Custom and select 0.0.0.0/0 and save the rule.

Your EC2 instance is now ready to accept incoming SSH connections.

Before moving ahead, go back to your EC2 dashboard and go to Instances. Select your instance. This will show a lot of data about your instance. The one we are interested in is your IP4 Public DNS. Copy this address.

Now go to your terminal and type the following

sudo ssh -i “mykeyfile” ubuntu@ip4-public-dns

Replace ip4-public-dns with the DNS that you copied from your instance.

Note: Amazon AWS has default usernames for AMIs based on the type of image which can be found on here.

When prompted, type yes.

If you get stuck at this step or if you get connection timed out errors, you can find more troubleshooting tips here and here.

Voila, you have now entered your EC2 instance using SSH and you can use this as any Ubuntu machine and install software on it.

I hope this article was able to help you get your EC2 instance fired up using Terraform.

--

--

Nyukeit

DevOps Engineer | Terraform, Ansible, Jenkins, Docker, Kubernetes, Cloud | I help in streamlining IT operations automation