DEV Community

Cover image for Master Terraform in 20 Minutes: Concepts, Commands & CI/CD
kaustubh yerkade
kaustubh yerkade

Posted on

Master Terraform in 20 Minutes: Concepts, Commands & CI/CD

Terraform has emerged as one of the most important DevOps technologies. Its the universal remote control for all your cloud resources.

In this blog, we’ll break down Terraform from zero to hero with examples, diagrams, real-world tips, and best practices for production.


Infrastructure

Infrastructure, in the context refers to all the foundational components that support the operation/lifecycle of applications, software, and services. It’s the base layer that powers everything in technology.

Infrastructure = Servers + Network + Storage + Databases + Security + Cloud Services

Types of Infrastructure-
1.Physical Infrastructure

  • Bare-metal servers
  • Switches
  • Routers
  • Data center hardware

2.Virtual Infrastructure

  • Virtual machines
  • Hypervisors (VMware, KVM)
  • Virtual networks

3.Cloud Infrastructure
AWS, Azure, GCP
EC2, S3, RDS, VPC
Kubernetes clusters

4.Application Infrastructure

  • APIs
  • CI/CD pipelines
  • Monitoring tools (Prometheus, Grafana)
  • Service mesh (Istio, Linkerd)

Problems Before Terraform

  • Lots of manual effort (for days/weeks)
  • No version control
  • Hard to reproduce environments
  • Each cloud had its own format
  • No single tool to manage multi-cloud

Before Terraform, IaC existed but was cloud specific:
AWS CloudFormation,Azure ARM Templates,Google Deployment Manager
These worked only for one cloud which implied no portability.

What is Terraform?

Terraform solved the above problems of automating, standardizing, and version-controlling infrastructure creation across all clouds using one simple, predictable, reusable system -

  1. Removed manual clicking in cloud consoles
  2. Allowed infrastructure to be written as code
  3. Made environments consistent (Dev, QA, Prod same)
  4. Enabled multi-cloud using one tool
  5. Added version control for infrastructure (Git)
  6. Provided predictable changes using terraform plan
  7. Fixed infrastructure drift
  8. Allowed reusable modules
  9. Improved team collaboration with remote state

Terraform is an Infrastructure as Code (IaC) tool. IaC means managing and provisioning infrastructure using code instead of manual clicks. It is created by HashiCorp that allows you to:

  1. Write infrastructure using code
  2. Version it like software
  3. Deploy it in multiple cloud providers
  4. Automate complex deployments
  5. Reproduce entire environments consistently

Terraform uses a declarative language called HCL (HashiCorp Configuration Language) to describe what you want, not how to do it.

Terraform is NOT only for cloud, it can manage literally anything with an API: cloud, on-prem, SaaS, networking, Kubernetes, security systems, and more.

Sample Terraform hcl Code to host a simple website Using NGINX on EC2

  • Create an AWS EC2 instance
  • Install NGINX automatically
  • Copy your site files to /usr/share/nginx/html
  • Expose it on port 80
provider "aws" {
  region = "ap-south-1"
}

resource "aws_instance" "nginx_server" {
  ami           = "ami-08e0ca9924195beba"   # Amazon Linux 2
  instance_type = "t2.micro"

  user_data = <<-EOF
    #!/bin/bash
    yum update -y
    amazon-linux-extras install nginx1 -y
    systemctl start nginx
    systemctl enable nginx

    # Create simple JS website
    cat <<HTML >/usr/share/nginx/html/index.html
    <html>
      <head><title>My JS Website</title></head>
      <body>
        <h1>Hello from NGINX + Terraform!</h1>
        <script src="app.js"></script>
      </body>
    </html>
HTML

    cat <<JS >/usr/share/nginx/html/app.js
    console.log("JS Loaded!");
JS
  EOF

  tags = {
    Name = "nginx-js-website"
  }

  vpc_security_group_ids = [aws_security_group.nginx_sg.id]
}

resource "aws_security_group" "nginx_sg" {
  name        = "nginx-allow-http"
  description = "Allow HTTP"

  ingress {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}
Enter fullscreen mode Exit fullscreen mode

How Terraform Can Manage All Types of Infrastructure ?

Terraform isn’t magic !! It works because it uses provider plugins that communicate with APIs of clouds, SaaS tools, and on-prem systems.

🗣️Everything Has an API !!

Terraform communicates using the service’s native API.

For Example:
AWS → uses AWS REST APIs
Kubernetes → uses K8s API server
GitHub → uses GitHub REST API
VMware → uses vSphere API

That means, If an API exists, Terraform can control it.

Providers (Plugins)

Terraform itself is an engine. It doesn’t know AWS, Azure, GitHub, or Kubernetes by default.

But Terraform uses: Providers
And each provider knows how to talk to a specific service.

Examples:

  • aws provider → talks to AWS API
  • azure provider → talks to Azure API
  • google provider → talks to GCP API
  • github provider → talks to GitHub API
  • kubernetes provider → talks to Kubernetes API
  • vault provider → talks to HashiCorp Vault

Each provider contains:

  1. API logic
  2. Authentication methods
  3. Resource definitions
  4. Create/Update/Delete operations Terraform just calls these providers.

Terraform Builds a Dependency Graph & Maintains State

Terraform figures out:

what to create first
what depends on what
what order to execute in

Terraform alos Maintains State !!
It remembers what exists, so it can update or delete correctly.


Terraform workflow -

Step Command What Happens Explanation (Short)
1. Write Code You create .tf files Define what infrastructure you want
2. Initialize terraform init Downloads providers Prepares Terraform to talk to AWS/Azure/GCP/K8s/etc.
3. Plan terraform plan Shows changes Terraform compares your code with current state
4. Apply terraform apply Creates/Updates resources Terraform uses provider APIs to build the infra
5. State Management Stores terraform.tfstate Keeps track of what exists to manage changes
6. Update/Delete plan + apply Modifies infra Terraform updates only what changed in code

High-Level Production Terraform Flow

To use Terraform for production/Dev Env: always use remote state, CI/CD pipelines, modules, separated environments, secure secrets, and strict approval workflows.

1.Developer updates .tf files
2.Creates PR → kicks off:

terraform fmt
terraform validate
terraform plan -out planfile

3.Team reviews plan
4.Only Approver merges PR
5.Pipeline applies plan against prod state
6.Terraform updates prod infra safely

Some Golden Rules for Using Terraform in Production

X Never run Terraform from your laptop
X Never store terraform.tfstate locally
X Never mix dev and prod in same state
X Never hardcode credentials

  • Always use CI/CD
  • Always use remote state
  • Always review every apply via PR
  • Store state in a remote backend (important):

AWS: S3 + DynamoDB
Azure: Blob Storage
GCP: GCS bucket

CI/CD will always read the shared state, no conflicts.


Terraform Commands Cheat Sheet

Basic Commands-

Purpose Command
Initialize project terraform init
Check syntax terraform validate
Format code terraform fmt
Show what will change terraform plan
Apply changes terraform apply
Destroy resources terraform destroy

State Commands-

Purpose Command
Show resources in state terraform state list
Show specific resource details terraform state show <resource>
Pull remote state terraform state pull
Replace a resource terraform taint <resource>
Remove a resource from state terraform state rm <resource>

Output and Variables-

Purpose Command
Show outputs terraform output
Show specific output terraform output <name>
Pass variable via CLI terraform apply -var="env=prod"
Use a variable file terraform apply -var-file="prod.tfvars"

Debugging-

Purpose Command
Enable debug logs export TF_LOG=DEBUG
Write logs to file export TF_LOG_PATH=log.txt

Hope you liked this blog & it cleared all your doubts about Terraform IaC. Let me know in the comments.

In the next blog we will learn about Terraform Syntax and how to write code for provider, resource, variable, output, and module. all written in HCL.

Stay tuned.

Meanwhile just remember- init → plan → apply → destroy
Bye !!!

Top comments (0)