Terraform

Terraform is an open-source infrastructure as code (IaC) tool created by HashiCorp. It enables users to define and provision infrastructure using declarative configuration files. With Terraform, you can manage various resources (like virtual machines, storage, networking, etc.) across a variety of cloud platforms (such as AWS, Azure, Google Cloud, etc.) as well as on-premises solutions.

Key Features
  1. Declarative Language: Terraform uses its own domain-specific language (HCL - HashiCorp Configuration Language) to define infrastructure, where you declare what you want, and Terraform figures out how to achieve it.

  2. Multi-cloud Support: It allows you to manage infrastructure across multiple providers (public and private clouds) in a unified way.

  3. Plan and Apply: Before applying changes, Terraform creates an execution plan to preview what it will do. This ensures safety and reduces the risk of unintended changes.

  4. State Management: Terraform maintains the state of your infrastructure in a state file. This is crucial because Terraform compares the desired state (in your configuration files) with the actual state of the infrastructure to determine the necessary actions.

  5. Modular: You can break down your infrastructure into reusable modules, making your code more manageable, reusable, and easier to collaborate on.

Basic Workflow

  1. Write: Define your infrastructure using configuration files (.tf files).
  2. Plan: Run terraform plan to see what changes will be made to achieve the desired state.
  3. Apply: Run terraform apply to implement the changes and provision the resources.
  4. Destroy: Run terraform destroy to remove all resources that were created.

Example: Create resources an AWS EC2 instance, a security group, a subnet and a VPC using Terraform (IaC) 

Prerequisites: Install Terraform, AWS CLI

First, login to AWS account from AWS CLI with 'aws configure' command

mkdir terraform_workspace
cd terraform_workspace

Step1: Create a file vpc.tf and define the VPC, Subnet, and Security Group

# Create a VPC
resource "aws_vpc" "my_vpc" {
  cidr_block = "10.0.0.0/16"
  tags = {
    Name = "MyVPC"
  }
}

# Create a public subnet
resource "aws_subnet" "my_subnet" {
  vpc_id            = aws_vpc.my_vpc.id
  cidr_block        = "10.0.1.0/24"
  availability_zone = "ap-south-1a"
  map_public_ip_on_launch = true
  tags = {
    Name = "MySubnet"
  }
}

# Create a security group to allow SSH inbound and ALL outbound traffic
resource "aws_security_group" "my_security_group" {
  vpc_id = aws_vpc.my_vpc.id

  # Inbound rule: Allow SSH from anywhere 
  ingress { 
     description = "Allow SSH inbound" 
     from_port = 22 
     to_port = 22 
     protocol = "tcp" 
     cidr_blocks = ["0.0.0.0/0"] # Allow access from any IP 
  }

  # Outbound rule: Allow all traffic to anywhere 
  egress { 
      description = "Allow ALL outbound" 
      from_port = 0 
      to_port = 0 
      protocol = "-1" 
      cidr_blocks = ["0.0.0.0/0"] # Allow access to any IP 
  }

  tags = {
    Name = "MySecurityGroup"
  }
}

Step2: Create a file main.tf and associate a EC2 instance with the VPC, subnet, and security group

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

# Create an EC2 instance in the public subnet, using the security group
resource "aws_instance" "my_ec2" {
  ami               = "ami-0522ab6e1ddcc7055"
  instance_type     = "t2.micro"
  subnet_id         = aws_subnet.my_subnet.id
  security_groups   = [aws_security_group.my_security_group.id]

  tags = {
    Name = "MyEC2Instance"
  }
}

# Output the public IP of the EC2 instance
output "instance_public_ip" {
  value = aws_instance.my_ec2.public_ip
}

Step 3: Initialize Terraform

Before Terraform can provision resources, you need to initialize the working directory, which downloads the provider plugins (in this case, for AWS)

terraform init


This will download necessary providers and prepare the environment.

Step 4: Preview the Infrastructure

This will preview an execution plan, detailing what will be created or changed

terraform plan


Step 5: Apply the Configuration

Run the following commands to deploy the VPC, subnet, security group, and EC2 instance

terraform apply


You’ll be prompted to confirm the action. Type yes to proceed.

Step 6: Verify the created EC2 Instance, Security Group (with defined Inbound, Outbound traffic), Subnet and VPC in AWS

Go to the AWS Management Console, navigate to the EC2 dashboard, and you should see the new instance running.





Step 7: Clean Up the Resources

You can destroy all the resources created by Terraform by running

terraform destroy


This example shows the basics of using Terraform to define, provision, and manage infrastructure in AWS. You can extend this by adding more resources, variables, and modules to create complex infrastructures.


👉 Difference between Terraform and AWS CloudFormation
  • Terraform:

    • Supports multiple cloud providers (AWS, Azure, Google Cloud, etc.) and third-party services.
    • Uses HCL (HashiCorp Configuration Language), offers strong modularity and reusable modules.
    • Requires managing a state file for tracking infrastructure.
    • Excellent for multi-cloud and hybrid environments.
    • Larger community and more diverse ecosystem.
  • CloudFormation:

    • AWS-only tool, tightly integrated with AWS services.
    • Uses JSON/YAML, no need to manage a state file (AWS handles it).
    • Supports change sets and rollback for safer deployments.
    • Good for AWS-native setups with deep integration.
    • Less flexible, but perfect for users fully within AWS.

In short: Terraform is ideal for multi-cloud setups and flexibility, while CloudFormation is best for AWS-centric environments and ease of AWS management.