SRE Bootcamp Series —EC2 Instance Creation using Terraform

Introduction and Hands on

Jansutris Apriten Purba
7 min readMay 18, 2021

Hallo Geeks, I hope you feeling good and enjoy your entire life.

Terraform by Hashicorp

Now i’d like to convey to you:

  • Infrastructure As Code
  • What Problem Does IaC Solve?
  • what is Terraform?
  • What is EC2?
  • What is EBS?
  • How to create EC2 Instance using Terraform

All of these knowledge is come from my ticket/sprint at AccelByte Inc. Happy Reading guys!

Infrastructure As Code

IaC Ilustration

Infrastructure as code is the process of managing and provisioning computer data centers through machine-readable definition files, rather than physical hardware configuration or interactive configuration tools.

As far as definitions go, this one isn’t bad, but it’s somewhat wordy. Let’s try and rewrite a simpler version:

Infrastructure as code (IaC) means to manage your IT infrastructure using configuration files.

The next question then becomes “Why would you want to do that?”

What Problem Does IaC Solve?

With the “what” out of the way, let’s turn our focus to the “why” of infrastructure as code. Why is it needed? What problem does it solve?

The Pain of Managing IT Infrastructure

Historically, managing IT infrastructure was a manual process. People would physically put servers in place and configure them. Only after the machines were configured to the correct setting required by the OS and applications would those people deploy the application. Unsurprisingly, this manual process would often result in several problems.

Cost

You’d have to hire many professionals to perform the necessary tasks at each step of the process, from network engineers to hardware maintenance technicians. All of those people need to be paid, obviously, but they also need to be managed.

Scalability and Availability

Since manual configuration is so slow, applications would often struggle with spikes in access, while the system administrators would be desperately trying to set up servers to manage the load. This necessarily impacts availability. If the organization didn’t have backup servers or even data centers, then the application could be unavailable for long periods.

Monitoring and performance visibility

A third major problem is Now that you have all of the infrastructure in place, how do you keep an eye on it to ensure it’s performing optimally? When you have an issue, how do you pinpoint exactly where in the infrastructure the issue is coming from? Is it the network, the server, or the application?

Inconsistency

If you have several people manually deploying configurations, discrepancies aren’t going to be unavoidable.

So, what is Terraform?

Terraform is a tool for building, changing, and versioning infrastructure safely and efficiently. Terraform can manage existing and popular cloud service providers(AWS, AZURE, GCP, Alibaba) as well as custom in-house solutions. It is one of the famous DevOps tools in market.

Terraform is an open-source infrastructure as a code software tool created by HashiCorp. It enables users to define and provision a datacenter infrastructure using a high-level configuration language known as Hashicorp Configuration Language (HCL).

Study Case:

Suppose you need 2 EC2 Instance, 2 EIP attached with that EC2 Instances, 1 Security Group, 1 Load Balancer etc, So you’ll manually create it in AWS Console/CLI/SDK.

Now in case, you need same thing, many times in your requirements, so this will be hectic work for you. So here comes Terraform, Write code once, use it (You can modify) according to you many times.

What is EC2?

Amazon Elastic Compute Cloud (Amazon EC2) is a web service that provides secure, resizable compute capacity in the cloud. It is designed to make web-scale cloud computing easier for developers. Amazon EC2’s simple web service interface allows you to obtain and configure capacity with minimal friction.

What is EBS?

relation between EC2 and EBS in AWS

Amazon Elastic Block Store (EBS) is an easy to use, high-performance, block-storage service designed for use with Amazon Elastic Compute Cloud (EC2) for both throughput and transaction intensive workloads at any scale. A broad range of workloads, such as relational and non-relational databases, enterprise applications, containerized applications, big data analytics engines, file systems, and media workflows are widely deployed on Amazon EBS.

How to Create EC2 Instance using Terraform

EC2 instance scenario

We’ll use AWS Cloud Provider for hands-on purpose. I’ll install the Terraform on EC2 Instance. I hope you have some basic knowledge on AWS EC2 Instance & one AWS account.

Installation of Terraform on Ubuntu 20.04 LTS

Download the latest version of Terraform from URL https://www.terraform.io/downloads.html . At the time of writing article, the latest version is 0.15.3.

To Download terraform from command, run following wget command:

$ wget https://releases.hashicorp.com/terraform/0.15.3/terraform_0.15.3_linux_amd64.zip

Now, unzip the downloaded file.

$ sudo apt install zip -y
$ sudo unzip terraform_0.15.3_linux_amd64.zip

This will output you a terraform file just move it to /usr/local/bin/ to execute the command.

$ sudo mv terraform /usr/local/bin/

Check the version

$ terraform version

This should provide you output similar to below

Terraform v0.15.3

Launching AWS EC2 Instance Using Terraform

Let’s make a directory and configure Terraform inside it. Run following commands

$ mkdir terraform
$ cd terraform

Now, make a configuration file. I am giving here the name as main.tf . You can give name as per your choice but remember the extension must be ‘tf’.

vim config.tf

Add the following terms provider AWS, your access key, secret key and region where you are going to launch ec2 instance. Here, I am going to use my favorite Oregon/us-west-2 region.

So for creating the EC2 Instance, we need basically AMI (Amazon Machine Images, instance type & tags.

provider "aws" {access_key = "YOUR-ACCESS-kEY"secret_key = "YOUR-SECRET-kEY"region = "us-west-2"}resource "aws_instance" "jansutris-test" {ami = "ami-0dd273d94ed0540c0"instance_type = "t2.micro"tags = {Name = "jan-testing"}root_block_device {volume_size= 100volume_type = "gp3"}Terraform init}

Each of the *_block_device attributes control a portion of the EC2 Instance's "Block Device Mapping". For more information, see the AWS Block Device Mapping documentation.

The root_block_device block supports the following:

  • delete_on_termination - (Optional) Whether the volume should be destroyed on instance termination. Defaults to true.
  • encrypted - (Optional) Whether to enable volume encryption. Defaults to false. Must be configured to perform drift detection.
  • iops - (Optional) Amount of provisioned IOPS. Only valid for volume_type of io1, io2 or gp3.
  • kms_key_id - (Optional) Amazon Resource Name (ARN) of the KMS Key to use when encrypting the volume. Must be configured to perform drift detection.
  • tags - (Optional) A map of tags to assign to the device.
  • throughput - (Optional) Throughput to provision for a volume in mebibytes per second (MiB/s). This is only valid for volume_type of gp3.
  • volume_size - (Optional) Size of the volume in gibibytes (GiB).
  • volume_type - (Optional) Type of volume. Valid values include standard, gp2, gp3, io1, io2, sc1, or st1. Defaults to gp2.

Terraform init

Now we will go to terminal, go to that path where you created main.tf and run the terraform init command.

tf init command

The terraform binary contains the basic functionality for Terraform, but it does not come with the code for any of the cloud providers, so when you’re first starting to use Terraform, you need to run terraform init to tell Terraform to scan the code, figure out which providers you’re using, and download the code for them. By default, the provider code will be downloaded into a .terraform folder, which is Terraform’s scratch directory. You need to run init any time you start with new Terraform code, and that it’s safe to run init multiple times (the command is idempotent).

Terraform plan

Now that you have the provider code downloaded, run the terraform plan command.

The plan command lets you see what Terraform will do before actually making any changes. This is a great way to sanity check your code before unleashing it onto the world. Anything with a plus sign (+) will be created, anything with a minus sign (–) will be deleted, and anything with a tilde sign (~) will be modified in place. In the preceding output, you can see that Terraform is planning on creating a single EC2 Instance and nothing else, which is exactly what you want.

Terraform apply

To actually create the Instance, run the terraform apply command.

You’ll notice that the apply command shows you the same plan output and asks you to confirm whether you actually want to proceed with this plan.
Type yes and hit Enter to deploy the EC2 Instance.

Now you deployed an EC2 Instance in your AWS account using Terraform. Let’s check whether it’s created or not. Open your AWS Console & go to EC2.

As disclaimer, This is for basic introduction of Terraform & We have deployed our first EC2 Instance using Terraform.

Hit clap if you find this article useful.

--

--