⚡An In-Depth Guide to Terraform Basics: Learn Infrastructure Management

⚡An In-Depth Guide to Terraform Basics: Learn Infrastructure Management

Overview

Terraform, developed by HashiCorp, is an infrastructure as code (IaC) tool that enables you to create, manage, and provision infrastructure resources efficiently and consistently across various cloud platforms.

Whether you are a developer, system administrator, or IT professional, understanding Terraform's basics is essential for automating infrastructure deployment.

In this blog post, I will try to cover all the basic terms that are used in Terraform, exploring its key concepts and syntaxes.

so let's get started!

What is Terraform?

Terraform is an open-source IaC tool that allows you to define and provision infrastructure resources through code. It provides a declarative approach for building and running applications and infrastructure. , What does the declarative approach mean?

Declarative plans are ones in which you specify outcomes, You let the tool take care of the steps required and focus on the outcomes which may be the high-level states, problems, or definitions of the infrastructure you want to build.

Terraform supports a wide range of cloud providers, including AWS, Microsoft Azure, and GCP, as well as various on-premises systems.

You have to define the list of resources and configurations that you want in your infrastructure.

Terraform examines each resource and configuration that has been provided to it and uses a graph-based approach to model and apply the desired state.

HCL (HashiCorp Configuration Language) is the language used in Terraform to write configuration files. It is designed to be human-readable and easy to understand.

HCL allows you to define and configure the infrastructure resources and their properties in a declarative manner.

Pre-requisite to learn Terraform

Although, there are not any necessary pre-requisite to learn Terraform, but it will be easy for you to grasp things if you are aware of the below terminologies and concepts:-

  1. Cloud Concepts: Basic understanding of Cloud computing is very necessary, you can start learning with Compute services and then you can learn Networking, storage, and security services of the cloud.

  2. Basic Programming Skills: Although Terraform uses its own configuration language HCL, having a basic understanding of programming concepts will help you grasp and write Terraform configurations more effectively.

  3. Knowledge of Networking and Infrastructure Concepts: Having a good understanding of networking concepts such as IP addressing, subnets, routing, and load balancing will help you design and configure network infrastructure using Terraform. Additionally, familiarity with infrastructure components like virtual machines, databases, and storage resources will be beneficial.

Terraform Advantages

Using Terraform instead of manually managing your infrastructure brings several advantages:

  1. Terraform can handle infrastructure management on multiple cloud platforms, giving you flexibility and options.

  2. The configuration language used in Terraform is easy to understand, making it simple to write infrastructure code without much effort.

  3. Terraform's state feature allows you to keep track of changes made to your resources throughout the deployment process, ensuring transparency and control.

  4. You can safely collaborate with others on infrastructure development by storing and sharing your Terraform configurations in version control systems. This enables better teamwork and prevents any confusion or conflicts.

Terraform Workflow

Terraform flow

When utilizing Terraform to deploy infrastructure, follow these steps:

  1. Scope - Determine the specific infrastructure requirements for your project.

  2. Author - Create the configuration files that describe your desired infrastructure setup.

  3. Initialize - Install the necessary plugins and dependencies that Terraform needs to manage the infrastructure.

  4. Plan - Generate a preview of the changes that Terraform will apply to align with your configuration.

  5. Apply - Execute the planned changes to bring your infrastructure in line with the desired state

Terraform Lifecycle:-

Terraform Tutorial for Beginners : Everything You Should Know

init: Once you have written your Terraform configuration file, the first command to execute is "Terraform init." This command initializes the working directory, performing various initialization steps to prepare it for use with Terraform.

Plan: Terraform enables a dry run using the "Plan" command. This allows you to preview the actions that will occur when you execute the Terraform configuration.

Apply: With the "Apply" command, Terraform provisions your infrastructure and updates the state file accordingly.

Destroy: When you want to delete all resources associated with a specific Terraform environment, the "Terraform Destroy" command can be used. This command ensures the removal of all configured resources.

How to Install Terraform?

Installing Terraform is as easy as other software, you just have to download the packages from the official Terraform website and set the environment variables(in the case of Windows system) on your system.

You should check out the steps provided on the official website of Terraform to download on any OS. Also, do check out the video for steps to follow for Windows OS users.

Terraform Components:-

Blocks

resource "aws_instance" "Demo" {
  ami = "abc123"

  network_interface {

  }
}

A block has a type (resource in this example). Each block type defines how many labels must follow the type keyword.

The resource block type expects two labels, which are aws_instance and Demoin the example above. A particular block type may have any number of required labels.

After the block type keyword and any labels, the block body is delimited by the { and } characters.

Within the block body, further arguments and blocks may be nested, creating a hierarchy of blocks and their associated arguments.

Providers

Terraform relies on plugins called providers to interact with cloud providers like AWS, GCP, Azure, SaaS providers, and other APIs.

Terraform configurations must declare which providers they require so that Terraform can install and use them.

If you want to use AWS services like S3, RDS, etc you must use AWS provider, similarly for Azure services, you must use Azure provider.

Additionally, some providers require configuration (like endpoint URLs or cloud regions) before they can be used.

you can also check out the Terraform registry for the partner providers available to use in Terraform.

Provider example:-

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

#Azure provider 
provider "azurerm" {
  features {}
}

#Kubernetes provider
provider "kubernetes" {
  version = "~> 1.10"
}

Resources

Resources are the most important component of Terraform, Each resource block describes one or more infrastructure objects, such as virtual networks, compute instances, or higher-level components such as DNS records.

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

#Terraform resource block to launch an EC2 instance
resource "aws_instance" "Demo" {
  ami           = "ami-02eb7a4783e7e9317"
  instance_type = "t2.micro"
  count         = 2
  key_name      = "testnew"
  tags = {
    Name = "Demo"
  }
}

In the above example, we are defining an AWS EC2 instance resource using the aws_instance block type. The Demo label is the name of this particular resource instance.

Inside the block, we specify various arguments that define the properties of the EC2 instance.

For example, we set the ami argument to specify the Amazon Machine Image ID, the instance_type argument to determine the instance type, the count argument to specify the number of instances and the key_name argument to specify the SSH key pair name for accessing the instance.

Additionally, we define tags for the instance using a map within the tags argument. This allows us to add metadata to the resource, such as the instance name and environment.

By creating this resource block, Terraform will provision an EC2 instance with the specified properties and manage its lifecycle based on your configuration.

Modules

In Terraform, modules are a way to encapsulate and organize reusable infrastructure configurations into a single package.

They provide a mechanism for code reuse, modularity, and abstraction, allowing you to create reusable building blocks for your infrastructure.

A module in Terraform consists of a collection of Terraform configuration files within a directory.

These files typically include a main configuration file (usually named main.tf) and may include other supporting files such as variables, outputs, and additional configuration files.

In Terraform, modules can be organized into a hierarchical structure, where you have a root module and child modules. Let's explore what these terms mean:

Root Module: The root module is the main Terraform configuration that serves as the entry point for your infrastructure.

It represents the top-level configuration and typically resides in its own directory. The root module can contain resources, variables, and other configuration elements directly defined within it.

Child Modules: Child modules are reusable modules that are invoked or called from within the root module.

Child modules can have their own configuration files, input variables, and outputs. They are typically stored in separate directories and can be reused across different projects or environments.

Example of a simple module code for creating an AWS S3 bucket in Terraform:

main.tf (Root Module):-

module "s3_bucket" {
 source = "./modules/s3_bucket"

  bucket = "my-s3-bucket"
  acl    = "private"

  control_object_ownership = true
  object_ownership         = "ObjectWriter"

  versioning = {
    enabled = true
  }
}

modules/s3_bucket/main.tf (Child Module):

resource "aws_s3_bucket" "example" {
  bucket = var.bucket_name
  region = var.region
}

modules/s3_bucket/variables.tf (Child Module):

variable "bucket_name" {
  type        = string
  description = "The name of the S3 bucket"
}

variable "region" {
    default = "region"

}

In this example, we have a root module (main.tf) that references a child module (s3_bucket) located in the modules/s3_bucket directory.

The child module defines an AWS S3 bucket resource using the aws_s3_bucket resource type from the AWS provider.

It takes input variables (bucket_name and region) to customize the bucket's configuration.

The root module invokes the child module using the module block, specifying the module's source (./modules/s3_bucket in this case). It provides values for the input variables (bucket_name and region) to configure the child module.

Terraform State: What is terraform.tfstate file?

In Terraform, state refers to the information and current state of your infrastructure that is stored and managed by Terraform itself.

It is a very important component of Terraform's operation and allows it to understand the current state of your infrastructure, track changes, and manage resources effectively.

Terraform maintains a state file, usually named terraform.tfstate, which is stored locally in the same directory as your Terraform configuration files.

This file contains information about the resources managed by Terraform, their attributes, dependencies, and other metadata.

The state file acts as a record of the resources Terraform has created. It keeps track of the relationship between resources, their attributes, and their configuration settings.

Terraform uses this information to plan and execute changes to your infrastructure.

When you run terraform apply or terraform destroy, Terraform compares the current state of your infrastructure (recorded in the state file) with the desired state specified in your Terraform configurations.

It then determines the necessary actions to bring your infrastructure into the desired state.

State file concept with an example

Let's take an example of creating an EC2 instance:-

Let's say you have a Terraform configuration file (main.tf) that defines an AWS EC2 instance:

resource "aws_instance" "ec2-new" {
  ami           = "ami-0c94855ba95c71c99"
  instance_type = "t2.micro"
}

When you run terraform apply for the first time, Terraform will create the EC2 instance and record its details (such as instance ID, IP address, etc.) in the state file.

On the next run, Terraform will read the state file to understand the current state of the instance and make any necessary changes based on your configuration.

Let's assume you modify the instance_type of the EC2 instance from t2.micro to t3.micro in your configuration:-

resource "aws_instance" "ec2-new" {
  ami           = "ami-0c94855ba95c71c99"
  instance_type = "t3.micro"
}

When you run terraform apply again, Terraform will compare the desired state (updated configuration) with the current state (recorded in the state file) and determine that the instance type needs to be changed.

It will then update the EC2 instance accordingly.

What is state locking in Terraform?

The state file serves as a form of lock file in Terraform because it tracks the current state of your infrastructure and ensures that changes made by multiple users or processes are synchronized correctly.

When running Terraform commands like terraform apply or terraform destroy, Terraform checks the state file to determine the desired state and make any necessary changes.

To prevent conflicts when multiple users or processes attempt to modify the same infrastructure concurrently, Terraform implements state locking mechanisms.

When a user initiates a Terraform operation, such as terraform apply, Terraform will try to acquire a lock on the state file to prevent other users or processes from modifying it simultaneously.

This ensures that only one operation can modify the state at a given time, maintaining consistency and preventing conflict conditions.

Summary

I hope you like the article on Terraform basics, I will continue to post more articles on Terraform practices, let me know your thoughts in the comment section.