Skip to main content

Command Palette

Search for a command to run...

Terraform

Published
7 min read
V

I am currently a B.Tech student pursuing Computer Science with a specialization in Data Science at I.T.S Engineering College. I am always excited to learn and explore new things to increase my knowledge. I have good knowledge of programming languages such as C, Python, Java, and web development.

What is Terraform?

Terraform is an open-source Infrastructure as Code (IaC) tool developed by HashiCorp that allows you to define, provision, and manage infrastructure using a declarative configuration language called HashiCorp Configuration Language (HCL) or JSON.

Key Features of Terraform:

  1. Declarative Configuration – You define the final infrastructure, and Terraform automatically determines how to achieve that state.

  2. Immutable Infrastructure – Rather than modifying existing resources, Terraform replaces them to ensure consistency.

  3. Execution Plan (terraform plan) – Terraform shows what changes will be made before applying them.

  4. State Management – Terraform maintains a state file (terraform.tfstate) that records infrastructure details for tracking.

  5. Provisioning Across Multiple Cloud Providers – Works with AWS, Azure, GCP, Kubernetes, and even on-premises infrastructure.

  6. Modules and Reusability – Allows defining reusable infrastructure components.

How Terraform Works:

  1. Write – Define infrastructure using .tf configuration files.

  2. Plan – Preview the changes Terraform will make (terraform plan).

  3. Apply – Deploy the infrastructure (terraform apply).

  4. Destroy – Remove infrastructure when it's no longer needed (terraform destroy).

Task 1:

Install Terraform on your system Refer to this link for installation.

To install Terraform on your system, follow the steps from the given link:

Step 1: Download Terraform

  • Visit the official Terraform download page.

  • Select the appropriate version for your operating system (Windows, Linux, or macOS).

Step 2: Install Terraform

For Windows:

  1. Extract the downloaded ZIP file.

  2. Move terraform.exe to a directory (e.g., C:\Terraform).

  3. Add this directory to your System Environment Variables > Path.

For Linux/macOS:

  1. Extract the file:

     sudo unzip terraform_<version>_linux_amd64.zip -d /usr/local/bin/
    
  2. Verify the installation:

     terraform -version
    

Step 3: Verify Installation

Run the following command to check if Terraform is installed correctly:

terraform -v

Why did we use terraform?

Terraform is widely used because it simplifies infrastructure management and automates provisioning, reducing manual errors. Here are some key reasons why it's preferred:

1. Infrastructure as Code (IaC)

Terraform allows you to define infrastructure in code (.tf files), making it easy to version, review, and reuse configurations.

2. Multi-Cloud Support

Terraform works with multiple cloud providers like AWS, Azure, GCP, Kubernetes, and even on-premise environments. This makes it easier to manage hybrid or multi-cloud infrastructure.

3. Declarative Approach

Instead of writing scripts (like in Ansible or Bash), Terraform lets you define the desired state of your infrastructure, and it takes care of how to achieve it.

4. Automated Provisioning & Deployment

With Terraform, you can create, update, or destroy infrastructure automatically using commands like:

  • terraform apply → Creates or updates infrastructure

  • terraform destroy → Deletes infrastructure

5. Execution Plan (terraform plan)

Before making any changes, Terraform provides an execution plan that shows what will be modified, ensuring transparency and preventing accidental changes.

6. State Management

Terraform keeps track of deployed resources using a state file (terraform.tfstate), ensuring consistency across deployments.

7. Modular & Scalable

Terraform supports modules, which help you create reusable infrastructure components, making management easier for large-scale environments.

What is Infrastructure as Code (IaC)?

Infrastructure as Code (IaC) is the practice of managing and provisioning infrastructure (servers, networks, databases) using code instead of manual processes. This enables automation, consistency, and scalability.

Types of IaC

  1. Declarative (What to Achieve) – Defines the desired state, and the tool figures out how to achieve it (e.g., Terraform, CloudFormation).

  2. Imperative (How to Achieve) – Specifies step-by-step commands to configure infrastructure (e.g., Ansible, Shell Scripts).

Benefits of IaC

Automation – Reduces manual effort
Consistency – Eliminates configuration drift
Scalability – Easily replicates infrastructure
Version Control – Stores configurations in Git for tracking

Example (Terraform)

resource "aws_instance" "example" {
  ami           = "ami-123456"
  instance_type = "t2.micro"
}

This ensures an AWS EC2 instance with the specified configuration is always running.

What is a Resource?

In Terraform, a resource is a fundamental building block that represents an infrastructure component such as a server, database, network, or storage bucket.

Key Points About Resources:

  • Defined in Terraform configuration files using the resource block.

  • Represents a real-world infrastructure object in a cloud provider (e.g., AWS EC2 instance, Azure VM, S3 bucket).

  • Can be modified, updated, or destroyed using Terraform commands.

Example of a Resource (AWS EC2 Instance)

resource "aws_instance" "example" {
  ami           = "ami-123456"
  instance_type = "t2.micro"
}
  • aws_instance → Resource type (AWS EC2 instance).

  • example → Resource name (used to reference the resource).

  • ami and instance_type → Configuration parameters.

How Terraform Manages Resources

  1. Create (terraform apply) → Provisions the resource.

  2. Update (terraform apply after changes) → Modifies the resource.

  3. Destroy (terraform destroy) → Deletes the resource.

What is a Provider?

A provider in Terraform is a plugin that enables Terraform to interact with a specific cloud platform, service, or API. Providers allow Terraform to create, manage, and destroy resources in platforms like AWS, Azure, GCP, Kubernetes, and many more.


Key Features of Providers:

  • Define how Terraform interacts with cloud services

  • Downloaded automatically when initializing Terraform (terraform init)

  • Supports multiple providers in a single configuration


Example: AWS Provider

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

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

resource "aws_instance" "example" {
  ami           = "ami-123456"
  instance_type = "t2.micro"
}
  • required_providers → Specifies the provider and version.

  • provider "aws" → Configures the AWS provider with the chosen region.

  • aws_instance → Uses the provider to create an EC2 instance.


Common Terraform Providers

  • AWShashicorp/aws

  • Azurehashicorp/azurerm

  • Google Cloudhashicorp/google

  • Kuberneteshashicorp/kubernetes

What is a State file in Terraform? What’s the importance of it?

The state file (terraform.tfstate) is a JSON file that Terraform uses to track the current state of deployed infrastructure. It helps Terraform understand what resources exist and how to manage them.

Importance of the State File

Tracks Infrastructure – Keeps a record of created resources.
Optimizes Performance – Speeds up Terraform operations by avoiding unnecessary API calls.
Prevents Configuration Drift – Ensures infrastructure matches the desired configuration.
Enables Collaboration – Remote state storage (S3, Terraform Cloud) allows teams to work together.

Best Practices

  • Use Remote State Storage (S3, Azure Blob, Terraform Cloud)

  • Enable State Locking (Prevents conflicts)

  • Never Edit Manually (Avoids inconsistencies)

What is the Desired and Current State?

In Terraform, the desired state and the current state are key concepts that define how Terraform manages infrastructure.

1. Desired State

  • The ideal infrastructure setup defined in Terraform configuration (.tf files).

  • Represents what you want the infrastructure to look like.

  • Example (main.tf file):

      resource "aws_instance" "example" {
        ami           = "ami-123456"
        instance_type = "t2.micro"
      }
    
    • This defines an EC2 instance with a specific AMI and instance type.

2. Current State

  • The actual state of resources running in the cloud.

  • Stored in the Terraform state file (terraform.tfstate).

  • Example (terraform state show aws_instance.example):

      {
        "id": "i-1234567890abcdef0",
        "ami": "ami-123456",
        "instance_type": "t2.micro"
      }
    
    • This represents the real EC2 instance running on AWS.

Terraform's Role

Compares the desired state with the current state.
Identifies differences (terraform plan).
Applies necessary changes to match the desired state (terraform apply).

Task 2:

Find the purpose of basic Terraform commands that you'll use often

terraform init

terraform init -upgrade

terraform plan

terraform apply

terraform validate

terraform fmt

terraform destroy

Here are the most commonly used Terraform commands and their purposes:


1. terraform init

Purpose: Initializes a Terraform working directory.

  • Downloads the required providers and modules.

  • Sets up the backend for state management (if configured).

  • Must be run before any other Terraform command.

Example:

terraform init

2. terraform init -upgrade

Purpose: Upgrades Terraform providers to the latest compatible versions.

  • Useful when updating Terraform configurations.

  • Ensures the latest security and feature updates.

Example:

terraform init -upgrade

3. terraform plan

Purpose: Shows the changes Terraform will make before applying them.

  • Helps review modifications without making actual changes.

  • Detects differences between the desired state and the current state.

Example:

terraform plan

4. terraform apply

Purpose: Create or update infrastructure based on the Terraform configuration.

  • Prompts for confirmation before applying changes.

  • After execution, update the state file (terraform.tfstate).

Example:

terraform apply

Auto-approve (no confirmation prompt):

terraform apply -auto-approve

5. terraform validate

Purpose: Checks the syntax and validity of Terraform configuration files.

  • Ensures there are no syntax errors or invalid arguments before applying changes.

Example:

terraform validate

6. terraform fmt

Purpose: Format Terraform configuration files to maintain code consistency.

  • Automatically fixes indentation and spacing issues.

Example:

terraform fmt

7. terraform destroy

Purpose: Deletes all Terraform-managed infrastructure.

  • Useful for cleaning up resources when they are no longer needed.

Example:

terraform destroy

Auto-approve (no confirmation prompt):

terraform destroy -auto-approve

More from this blog

Vanshika Sharma

38 posts

B.Tech Data Science, Expert in C, Python, Java, and Full-Stack Web Development. Knowledge in Problem Solving Languages.