Terraform Basics: Installation and EC2 Instance Provisioning

Tejashree Salvi
8 min readJun 5, 2023

--

As a DevOps engineer, one of our key responsibilities is to create and manage infrastructure efficiently. So get ready to explore and witness the magic of Terraform as we will be simplifying and streamlining infrastructure provisioning and management.

Let's get Started!

➤ What is Infrastructure as Code (IaC)?

Infrastructure as Code (IaC) refers to the practice of managing and provisioning infrastructure resources(servers, networks, databases, etc) using code rather than using the Graphical User Interface (eg. AWS console).

➤ What is Terraform?

Terraform is an open-source tool that helps implement IaC.

It allows you to write code in a specific language called HashiCorp Configuration Language (HCL) to describe the desired state of your infrastructure.

When you run Terraform, it reads your code and interacts with various cloud providers (like AWS, Azure, or GCP) to create or modify the resources based on your code’s instructions. Terraform automates the provisioning and management of your infrastructure, ensuring that it matches the defined state in your code.

Here’s why the manual approach falls short and why Terraform is a better choice:

  1. Manual creation of resources often has manual steps and configurations which cause inconsistency in different environments and are prone to human errors. Terraform enables consistent and reproducible infrastructure deployments. It’s flexible to provision infra across multiple cloud providers with the same template code.
  2. Manual resource creation lacks the ability to scale easily. Terraform manages infra, allowing you to scale your resources easily by adjusting the number of instances.
  3. When creating resources manually, it becomes challenging to track the changes. With Terraform, Infra is defined in a code that makes easy-to-use Version control ie. Git.
  4. Manual resource creation lacks auditing. Terraform state management and code-based infra provide a transparent auditing record of all the changes made to infra.

➤ Install / Setup Terraform on Linux System

Step 1: The command will update the system and is used to install the packages gnupg and software-properties-common along with their dependencies.

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

Step 2: The command will download the HashiCorp GPG key, import it into the keyring, and save it as /usr/share/keyrings/hashicorp-archive-keyring.gpg.

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

Step 3: The command is used to display the fingerprint of the GPG key stored in /usr/share/keyrings/hashicorp-archive-keyring.gpg.

gpg --no-default-keyring \
--keyring /usr/share/keyrings/hashicorp-archive-keyring.gpg \
--fingerprint

Step 4: The command is used to add a new software repository entry for HashiCorp to the system’s package sources. This allows you to install software from the HashiCorp repository using the package manager.

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

Step 5: This command installs the Terraform package on your system.

sudo apt update
sudo apt-get install terraform

Hey, You have successfully installed Terraform on your system.

Terraform uses a declarative Syntax, which means you describe what you want your infrastructure to look like, and Terraform figures out how to achieve that state. Awesome right?

➤ HCL (HashiCorp Configuration Language) Basics

HCL is a configuration language used by Hashicorp tools, including Terraform. HCL syntax is similar to JSON, with a more human-friendly approach.

In Terraform, it is used to write the configuration files that describe the desired state of your infrastructure. These files typically have a .tf extension and contains the definitions, variables, and config details.

Important Terminologies of HCL: Terraform

Blocks:

Blocks represent different entities or components in your infrastructure configuration, such as providers, resources, variables, data sources, and more.

HCL code is organized into blocks, which define different objects or resources. Each block starts with an opening brace { and ends with a closing brace }.

Following are some of the blocks:

⁕ Provider:

Provider blocks contain authentication details and configuration settings required to connect to the provider’s API.

A provider is a plugin that interacts with a specific cloud or infrastructure platform that enables to create, update and delete resources in that platform.

⁕ Resource:

A resource is a specific infrastructure object that you want to manage. It can be instances, databases, network interface, etc

Resources have attributes that define their configurations.

Arguments:

Arguments are key-value pairs defined within a block.

Inside a block, you define attributes that specify the properties and settings of the resource. Attributes have a key-value structure.

⫸ Variable:

Variables allow you to define reusable values that can be used across your code

They can be defined at different levels (e.g., in the main Terraform configuration or within modules) and can have default values. It allows you to parameterize the code.

⫸ Module:

Terraform allows you to break down your infrastructure configuration into reusable modules.

Modules can be created and used across different Terraform projects. It allows you to organize and encapsulate infrastructure code for better reusability.

To configure AWS CLI using your secret key and access key

⫸ Generate the Access Key and Secret Key

  • Search IAM AWS Service → UsersCreate User (Enter details)
  • To set permissions: Select Attach policies directly permission options
  • Review the user details and Permissions → Click Create User
  • The users will be created successfully. Click on Username terraform-user
  • Go to Security Credentials → Access keys → click Create access key
  • In Access key best practices & alternatives: Select Command Line Interface (CLI) option
  • The set description tag is optional. Hence click on Create access key

We have successfully generated Access Key and Secret Key

⫸ Install AWS CLI and configure:

sudo apt-get install awscli

Open a terminal and run the following command:

aws configure

This will prompt you to enter the Access Key(Unique identifier) and Secret Access Key, skip the region, and output format.

You have successfully configured AWS CLI. Now you can run aws ad-hoc commands from your terminal.

☆ Let’s provision EC2 Instance using Terraform ☆

terraform init → terraform plan → terraform apply

Create a file: aws.tf

terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.0"
}
}
}

In the above code,

  • terraform is a block used to configure global settings for terraform configuration.
  • required_providers specify the provider required ie aws in this case.
  • aws is sourced from “hashicorp/aws” and the version is set to equal to greater than 4.0

⫸ terraform init

The terraform init command is used to initialize a new or existing Terraform configuration.

During initialization, Terraform will display the progress and provide feedback on the process. If any provider plugins or dependencies need to be downloaded, they will be fetched and installed.

Run the command to initialize and download dependencies:

terraform init

Terraform has been successfully initialized!

Create a file: providers.tf

provider "aws" {
region = "us-east-1"
}

The above code is a Terraform configuration block that specifies the AWS provider and sets the region to “us-east-1”. Other configuration parameters(access key, secret access key) we have already set.

Create a file: aws_instance.tf

resource "aws_instance" "my_instance" {
ami = "ami-053b0d53c279acc90"
instance_type = "t2.micro"
tags = {
"Name": "terra-instance"
}
}

The above code is a Terraform resource block that defines an AWS EC2 instance with specific attributes.

  • ami = "ami-053b0d53c279acc90": This sets the AMI (Amazon Machine Image) ID for the EC2 instance.
  • instance_type = "t2.micro": This sets the instance type for the EC2 instance.
  • tags = { "Name" = "terra-instance" }: This assigns tags to the EC2 instance using a map. Tags are useful for organizing and identifying resources in AWS.

⫸ terraform plan

The terraform plan command is used to create an execution plan for your Terraform configuration. Terraform will read the configuration, analyze the state and display the plan.

Note that terraform plan does not make any changes to your infrastructure. It only provides a preview of the changes that Terraform will make based on configurations.

Run the command to review the configurations

terraform plan

⫸ terraform apply

The terraform apply command is used to apply the changes defined in your Terraform configuration and create or modify resources

  • Terraform will prompt you to review the changes. If the plan looks correct and you wanna proceed with the changes, type yes and enter.

Please note that applying changes with terraform apply can have real-time effects on your infrastructure. Review the plan carefully and then apply the changes.

It successfully created an EC2 instance terra-instance

To destroy the Infrastructure created by terraform code.

terraform destroy

Great! If you have come to the end. This indicates you are really interested in Terraform. We will learn more about HCL in the next blog.

This is #Day1 of the #terraweek Challenge with Shubham Londhe

Do add some claps, if you liked the article 👏

Follow for more such content ❤

LinkedIn: https://www.linkedin.com/in/tejashree-salvi-003aa2195/

--

--

Tejashree Salvi
Tejashree Salvi

Responses (2)