10th Week :- Terraform in DevOps: Complete Guide with AWS, Kubernetes & CI/CD Examples

Lav kushwahaLav kushwaha
6 min read

πŸ“Œ 1. What is Terraform?

Terraform is an Infrastructure as Code (IaC) tool developed by HashiCorp.
It allows DevOps engineers, cloud architects, and developers to define, provision, and manage infrastructure using a declarative configuration language (HCL - HashiCorp Configuration Language).

Instead of manually creating resources in a cloud provider’s console, you write code that describes the desired infrastructure, and Terraform takes care of creating, updating, and managing it.

Think of Terraform like a blueprint for your cloud. You describe what you want, and Terraform builds it for you.


πŸ“Œ 2. Why Terraform in DevOps?

In DevOps, speed, consistency, and automation are key. Terraform helps achieve these by:

  • Automating infrastructure setup and tear-down

  • Version-controlling infrastructure changes like software code

  • Ensuring consistency across environments (Dev, Staging, Prod)

  • Integrating easily with CI/CD pipelines


πŸ“Œ 3. Key Benefits of Terraform πŸ†

BenefitDescription
Cloud Agnostic ☁Works with AWS, Azure, GCP, Kubernetes, VMware, etc.
Declarative Syntax πŸ“œYou describe what you want, not how to do it
Immutable Infrastructure πŸ›‘Updates replace resources safely, avoiding config drift
State Management πŸ—‚Tracks infrastructure state for accuracy
Collaboration Ready 🀝Works with Git for team-based infra management
Scalable πŸ“ˆHandles large, complex deployments easily

πŸ“Œ 4. Terraform Core Concepts 🧠

  1. Provider – Defines the cloud or platform (e.g., AWS, Azure, GCP, Kubernetes).

  2. Resource – The infrastructure component (EC2 instance, S3 bucket, VPC, etc.).

  3. Variables – Parameters for dynamic configurations.

  4. State File (terraform.tfstate) – Keeps track of created resources.

  5. Modules – Reusable sets of Terraform files.

  6. Plan & Apply – Plan previews changes, Apply executes them.


πŸ“Œ 5. Terraform Use Cases πŸ“Œ

a) Multi-Cloud Deployments

Easily deploy resources to AWS + Azure + GCP simultaneously.

b) Immutable Infrastructure

Easily replace outdated infrastructure instead of patching manually.

c) Infrastructure Version Control

Keep track of infrastructure changes in GitHub.

d) Automated Environment Provisioning

Spin up staging/prod environments in minutes.


πŸ“Œ 6. Sample Terraform AWS Deployment ☁

Here’s an example AWS EC2 Instance creation with Terraform.

Step 1: Install Terraform

# For Linux / Mac
brew tap hashicorp/tap
brew install hashicorp/tap/terraform

# For Windows
choco install terraform

Step 2: Create Terraform Files

πŸ“‚ Folder structure:

terraform-aws-demo/
  β”œβ”€β”€ main.tf
  β”œβ”€β”€ variables.tf
  β”œβ”€β”€ outputs.tf

main.tf

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

resource "aws_instance" "web" {
  ami           = "ami-0c02fb55956c7d316" # Amazon Linux 2
  instance_type = "t2.micro"

  tags = {
    Name = "Terraform-EC2"
  }
}

variables.tf (optional for customization):

variable "region" {
  default = "us-east-1"
}

outputs.tf:

output "instance_ip" {
  value = aws_instance.web.public_ip
}

πŸ“Œ 7. Deploy to AWS with Terraform πŸš€

# Step 1: Initialize Terraform
terraform init

# Step 2: Preview what will be created
terraform plan

# Step 3: Apply changes (create resources)
terraform apply

# Step 4: Destroy infrastructure (when no longer needed)
terraform destroy

πŸ“Œ 8. Terraform in CI/CD DevOps Workflow πŸ”„

Terraform fits perfectly into a DevOps pipeline:

  1. Write β†’ Create .tf files describing infra.

  2. Plan β†’ Run terraform plan in CI to preview changes.

  3. Review β†’ Code review via Pull Requests.

  4. Apply β†’ Auto-deploy on merge to main branch.

  5. Monitor β†’ Track infra drift with Terraform Cloud.


πŸ“Œ 9. Advanced Terraform Features πŸ’‘

FeatureWhy it’s Useful
Remote State StorageShare state between team members via S3, GCS, Azure Blob, etc.
WorkspacesManage multiple environments (dev, staging, prod)
ModulesReusable infrastructure blueprints
Data SourcesUse existing resources without recreating
ProvisionersRun scripts on created instances

πŸ“Œ 10. Real-Life Example: AWS VPC + EC2 with Terraform πŸ—

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

# Create VPC
resource "aws_vpc" "main" {
  cidr_block = "10.0.0.0/16"
}

# Create Subnet
resource "aws_subnet" "subnet1" {
  vpc_id            = aws_vpc.main.id
  cidr_block        = "10.0.1.0/24"
  availability_zone = "us-east-1a"
}

# Create EC2 Instance
resource "aws_instance" "web" {
  ami           = "ami-0c02fb55956c7d316"
  instance_type = "t2.micro"
  subnet_id     = aws_subnet.subnet1.id

  tags = {
    Name = "Web-Server"
  }
}

πŸ“Œ 11. AWS Example β€” Deploy EC2 & VPC ☁

Folder Structure

terraform-aws/
  β”œβ”€β”€ main.tf
  β”œβ”€β”€ variables.tf
  β”œβ”€β”€ outputs.tf

main.tf

provider "aws" {
  region = var.aws_region
}

# Create VPC
resource "aws_vpc" "main" {
  cidr_block = "10.0.0.0/16"
}

# Create Subnet
resource "aws_subnet" "subnet1" {
  vpc_id            = aws_vpc.main.id
  cidr_block        = "10.0.1.0/24"
  availability_zone = "us-east-1a"
}

# Create EC2 Instance
resource "aws_instance" "web" {
  ami           = var.ami_id
  instance_type = "t2.micro"
  subnet_id     = aws_subnet.subnet1.id

  tags = {
    Name = "Terraform-Web-Server"
  }
}

variables.tf

variable "aws_region" {
  default = "us-east-1"
}

variable "ami_id" {
  default = "ami-0c02fb55956c7d316" # Amazon Linux 2
}

outputs.tf

output "instance_ip" {
  value = aws_instance.web.public_ip
}

Deployment

terraform init
terraform plan
terraform apply
terraform destroy # To clean up

πŸ“Œ 12. Kubernetes Example β€” Deploy an NGINX Pod 🐳

Terraform can also manage Kubernetes clusters and workloads.

Pre-requisites

  • A running Kubernetes cluster (EKS, AKS, GKE, or Minikube)

  • kubectl configured

main.tf

provider "kubernetes" {
  config_path = "~/.kube/config"
}

resource "kubernetes_namespace" "demo" {
  metadata {
    name = "terraform-demo"
  }
}

resource "kubernetes_deployment" "nginx" {
  metadata {
    name      = "nginx-deploy"
    namespace = kubernetes_namespace.demo.metadata[0].name
  }

  spec {
    replicas = 2
    selector {
      match_labels = {
        app = "nginx"
      }
    }
    template {
      metadata {
        labels = {
          app = "nginx"
        }
      }
      spec {
        container {
          image = "nginx:latest"
          name  = "nginx"
          port {
            container_port = 80
          }
        }
      }
    }
  }
}

Deploy to Kubernetes

terraform init
terraform apply

πŸ“Œ 13. Terraform + CI/CD Pipeline (GitHub Actions Example) πŸ”„

You can automate Terraform deployments using GitHub Actions.

.github/workflows/terraform.yml

name: Terraform Deploy

on:
  push:
    branches: [ "main" ]

jobs:
  terraform:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v2

      - name: Setup Terraform
        uses: hashicorp/setup-terraform@v2

      - name: Terraform Init
        run: terraform init

      - name: Terraform Plan
        run: terraform plan

      - name: Terraform Apply
        run: terraform apply -auto-approve

Now, every push to main will auto-deploy infrastructure

πŸ“Œ 14. Summary ✨

Terraform is a must-have tool in DevOps for managing cloud infrastructure in a consistent, automated, and scalable way. Whether you’re building a small project or a multi-cloud enterprise system, Terraform helps you:

βœ… Save time
βœ… Reduce human errors
βœ… Improve collaboration
βœ… Scale infrastructure efficiently


πŸ’‘ Pro Tip: Use Terraform Cloud for remote state, team collaboration, and secure secret management.

0
Subscribe to my newsletter

Read articles from Lav kushwaha directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Lav kushwaha
Lav kushwaha