SoftServe SoftServe
SoftServe

SoftServe

3.93

15 reviews

WHAT IS TERRAFORM: HOW TO INSTALL AND USE IT

25.07.2024

I am Alex, a seasoned DevOps Engineer with six years of IT experience. My journey has taken me from SysOps admin and IT Manager roles to my current focus on DevOps, a transition I made three years ago. Along the way, I have gained six certifications: AWS SysOps Administrator, AWS Architect Associate, DevOps Engineer Professional (Amazon Web Services - AWS Certificate), Oracle Certified Foundations Associate, Oracle Cloud Infrastructure Architect Associate, and HashiCorp Terraform Associate. 

Today, I am excited to introduce you to Terraform, walk you through how to install it, and show you how to use it effectively. In this blog article, we will cover: 

  • Installing Terraform and AWS CLI
  • Setting up the AWS provider
  • Creating and destroying an EC2 instance using Terraform 

WHAT IS TERRAFORM

Early in my DevOps career, I was introduced to the concept of Infrastructure as Code (IaC), which completely captivated me. Terraform has become an invaluable tool in my arsenal, enabling me to automate the provisioning of cloud resources efficiently.

The initial setup might seem daunting for beginners to Terraform. Fear not; the process is simpler than it appears.

The tools are widely divided into two major categories:

infrastructure as a code tools examples

1. Infrastructure Orchestration 

What it Does: Automatically sets up and connects different parts of a computer system, like putting together pieces of a puzzle.
Why it Matters: Makes sure all parts work together smoothly and efficiently, without needing manual intervention.

2. Configuration Management

What it Does: Keeps the settings and configurations of computer systems consistent and correct.
Why it Matters: Ensures everything stays in the right setup, making systems reliable and easier to manage. 

Terraform is one of the most popular Infrastructure-as-code (IaC) tools used by DevOps teams to automate infrastructure tasks. It is used to automate the provisioning of your cloud resources. 

TERRAFORM INSTALLATION

Let's get started with the essential requirements: 

  • Patience & Enthusiasm
  • Basic Understanding of AWS*
  • AWS Account*  

* You can use various providers like Azure, Google Cloud, Alibaba, and others, but the AWS provider is my preference. 

Terraform installation is very simple. Download, install, and use it: https://developer.hashicorp.com/terraform/install 

AWS CLI INSTALLATION 

Since I am familiar with AWS, we will be working with AWS to provision our infrastructure using Terraform, so we also need to install AWS CLI. Follow the steps listed to install the latest version of AWS CLI for your OS: https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html

installation of aws cli

Terraform uses AWS CLI to make API calls to execute any provisioning task. Log in to AWS Console and create a Terraform user. The user needs programmatic access to AWS, so check the corresponding checkbox only. 

create a terraform user

For now, provide the administrative role to this user. However, it is recommended to follow the principle of least privilege when working on projects. 

providing role to terraform user

Once the user is successfully created, note the Access Key ID and Secret Access Key. 

We need to configure these credentials in the AWS CLI we just installed. Open the terminal and run the “aws configure” command to configure default credentials. Select the region of your choice, if required. 

configure credentials in terraform

With this, we have successfully set up our environment to begin working with Terraform and AWS. 

Note: Terraform can make API calls without AWC CLI if you hardcode credentials or use another method to access AWS. 

TERRAFORM PROVIDERS  

To work with a cloud provider like AWS using Terraform, you need to set up a module for it. This involves downloading the necessary files and specifying the version of the AWS provider you want to use. 

To start your Terraform project, create a new directory on your computer and open it in your code editor. All your Terraform code will go into files with the ".tf" extension in this directory. Begin by creating a file called "providers.tf" and add the provider configuration as shown below: 

configuration for provider.tf file

As previously stated, Terraform utilizes HCL syntax, a declarative configuration language that enables us to specify the cloud resources we wish to provision. In the "providers.tf" file, we define a Terraform block containing another block for specifying required providers. 

The code snippet above directs Terraform to set up the AWS provider with version 5.3.0. Save the "providers.tf" file. To initialize our Terraform project, execute the "terraform init" command in the root directory.  

RESOURCES 

Create another file named “main.tf” in the same directory. The intention of creating this file is to declare the resources we want to create in AWS. It is completely okay to skip creating this file and just append the “providers.tf” file with the code below.  

However, creating separate files helps manage the Terraform code better. Add the code below to the “main.tf” file. 

adding code to main.tf

Here we have declared a resource block of type “aws_instance”. This instructs Terraform that we want to create an EC2 instance resource in AWS with the given attributes.  

Note: To identify the correct resource type and associated attributes, refer to the Terraform Registry

The second parameter is “ec2”, which is an internal identifier. Its purpose is to refer to this particular EC2 instance elsewhere in the code. We can assign any name to this identifier. 

Amongst the resource attributes, we have declared the AMI, which defines the image we want to use to create this EC2 instance. We have also specified the “instance_type” to define the size of the EC2 instance to be created. 

Additionally, we have assigned a tag “Name” with the value “MyFirstEC2UsingTerraform”. 

With this, we have successfully created the code to create an EC2 instance in AWS using Terraform. 

TERRAFORM PLAN

The "plan" command serves to validate the resource declarations made with Terraform. It reviews all Terraform configuration files, detecting any syntax errors, version mismatches, and other issues. 

Moreover, it cross-references the code with the state file to determine and present a summary of the resources that will be created, updated, or deleted if we decide to execute the current version of the code. This feature provides a useful overview of changes before applying them to the intended infrastructure. 

To utilize this feature, navigate to your code directory and execute the "terraform plan" command, then observe the output. 

TERRAFORM BACKEND 

Backends primarily determine where Terraform stores its state. By default, Terraform implicitly uses a backend called local to store state as a local file on disk. Terraform supports multiple backends that allow remote service-related operations. Some of the popular backends include: 

  • S3
  • Consul
  • Terraform Cloud 

CHALLENGE WITH LOCAL BACKEND

Nowadays, an entire team handles and collaborates on a Terraform project. Storing the state file on the local laptop will not allow collaboration. I personally prefer Terraform Cloud. 

DECLARING VARIABLE VALUES IN TERRAFORM

When variables are declared in your configuration, they can be set in several ways: 

  1. Variable Defaults
  2. Variable Definition File (*.tfvars)
  3. Environment Variables
  4. Setting Variables in the Command Line 

OUTPUTS.TF

Output values make information about your infrastructure available on the command line and can expose information for other Terraform configurations to use. 

outputs.tf code

The tree structure in Terraform looks like this: 

tree structure in Terraform

Now just write “terraform apply”, observe the output, and then write “yes” on the prompt. 

You have EC2 created using Terraform. Congrats. 

To delete the resource, just “terraform destroy”. 

TERRAFORM CODE IN NOTEPAD

You can write Terraform code in Notepad, and it will not have any impact. 

terraform in notepad

But of course, there is a need for a better application that allows us to develop code faster. 

terraform vs visual studio code meme

TERRAFORM CHEAT SHEET

CLI commands: 

  • Initialize Terraform: terraform init
  • Create a plan: terraform plan
  • Apply the plan: terraform apply
  • Destroy the infrastructure: terraform destroy
  • To import an existing infrastructure: terraform import [resource_name] [resource_id]
  • To see the state of the infrastructure: terraform show
  • To list all the resources that Terraform is managing: terraform state list
  • To get detailed information about a specific resource: terraform state show [resource_name]
  • To validate the syntax of the Terraform files: terraform validate
  • To see a list of all the available Terraform providers: terraform providers
  • To see the version of Terraform currently installed: terraform version
  • To override a variable value from the command line: terraform apply -var '[variable_name]=[value]

terraform memes

One of the best aspects of Terraform is its versatility. Once you master the basics, you can easily work with all providers.  

I hope you found this guide helpful. 

*AUTHOR: ALEXANDRU DUMITRIU | SOFTSERVE SENIOR AWS DEVOPS ENGINEER