Provisioning EC2 Instance with Terraform

by
, posted

Table of Contents

What is Terraform

Terraform is an infrastructure as code (IaC) tool that allows users to define and provision infrastructure resources across various cloud providers and services using a declarative configuration language.

Imagine being able to define the instances, databases, networking rules, and security groups for an application running on AWS in the form of syntax or code. That is what IaC tool enables a user to achieve. Terraform uses a specific format to declare the infrastructure known as HashiCorp Configuration Language (HCL).

Terraform enables the creation, modification, and deletion of infrastructure resources in a consistent and reproducible manner. It supports a wide range of cloud platforms, including Amazon Web Services (AWS), Microsoft Azure, Google Cloud Platform (GCP), and more.

Terraform was open source & released under Mozilla Public License (MPL v2) since 2014. Recently on 15th Aug ‘23 Hashicorp announced changing its license to Business Source License (BSL). This decision has faced backlash from the community, leading to the development of a new fork called OpenTF

Prerequisites

To get ready for provisioning resources using Terraform on AWS, we have certain pre-conditions:

Terraform

On macOS run the following commands to install Terraform.

$ brew tap hashicorp/tap
$ brew install hashicorp/tap/terraform

For Windows & Linux check the official docs for installation.

To verify the successful installation run:

$ terraform --version
Terraform v1.5.7
on darwin_arm64

aws-cli

You also need to have aws-cli installed on your machine – Instructions here. Once you are done with installation authorize your AWS account by configuring credentials

Run this command to verify the authorization. It should return your AWS account’s unqiue 12-digit number:

$ aws sts get-caller-identity
{
    "UserId": "AIDAQJICDY7KWY752N5EI",
    "Account": "012345678901",
    "Arn": "arn:aws:iam::012345678901:user/cosmicqbit"
}

Key Pair

Last thing you need is a Key Pair to access your AWS account programatically. You can find the instructions on generating KeyPair here. At the end download the key on your local machine and save it into a separate directory, say aws-terraform.

Provisioning EC2 with Terraform

Now let’s see how to provision an AWS EC2 Instance using Terraform. Open the folder where you saved your KeyPair in VSCode. Create a new file named main.tf. Copy paste the following contents into it:

provider "aws" {
    region = "ap-south-1"
}

resource "aws_instance" "web" {
    ami = "ami-05552d2dcf89c9b24"
    instance_type = "t2.micro"
    key_name = "terra"
}

In the first block we define the provider which is “aws” and the region in which we want to define our resources. In the resource block we declare the resource type “aws_instance” and resource name “web”. Inside the block other related metadata is defined.

ami defines the ID of image used in the EC2. Instance type is set to t2.micro because we want to go with free tier. key_name is the name of the KeyPair you have saved in your current directory already.

Next save the file and launch the terminal in current directory.

We’re now good to go. Let’s apply our infrastructure! But before we do this, we need to initialize our providers via terraform init.

Terraform init

$ terraform init

Initializing the backend...

Initializing provider plugins...
- Reusing previous version of hashicorp/aws from the dependency lock file
- Using previously-installed hashicorp/aws v5.16.2

Terraform has been successfully initialized!

[...]

Terraform validate

To validate the code run:

$ terraform validate

Success! The configuration is valid.

Terraform plan

Let’s have a look at the upcoming changes that Terraform will create by running terraform plan.

The output will look something like this:

$ terraform plan

Terraform will perform the following actions:

  # aws_instance.web will be created {..}
  
Plan: 1 to add, 0 to change, 0 to destroy.

The + indicator shows that those resources will be created by Terraform.

Terraform apply

Let’s now apply our changes via terraform apply. Terraform will preview the changes again and will then prompt you before applying them.

$ terraform apply

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: yes

aws_instance.web: Creating...
aws_instance.web: Still creating... [10s elapsed]
aws_instance.web: Still creating... [20s elapsed]
aws_instance.web: Creation complete after 23s [id=i-04a1b819d5105]

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

That’s it. Our the EC2 Instance we created is now available at AWS. Navigate to your AWS EC2 Instances tab and check running instances.

Terraform destroy

Let’s complete this small tutorial by removing all of our resources by running terraform’s destroy command.

$ terraform destroy

Do you really want to destroy all resources?
  Terraform will destroy all your managed infrastructure, as shown above.
  There is no undo. Only 'yes' will be accepted to confirm.

  Enter a value: yes

aws_instance.web: Destroying... [id=i-04a1b819dd6fb5105]
aws_instance.web: Still destroying... [id=i-04a1b819dd6fb5105, 10s elapsed]
aws_instance.web: Still destroying... [id=i-04a1b819dd6fb5105, 20s elapsed]
aws_instance.web: Still destroying... [id=i-04a1b819dd6fb5105, 30s elapsed]
aws_instance.web: Destruction complete after 30s

Destroy complete! Resources: 1 destroyed.

That completes our small tutorial of provisioning EC2 Instance using Infrastructure as a Code (IaC) tool Terraform. By utilizing the terraform commands such as init, validate, plan, apply, and destroy, we were able to define aws resource – EC2 Instance in a declarative and efficient manner.

Reply via mail

Your Signature