8. ποΈ Terraform: Infrastructure as Code (IaC) from Scratch for DevOps Engineers
Open to Work | Cloud & DevOps Engineer | AWS | Kubernetes | Terraform | CI/CD | Automations | Available for Full-Time / Freelance / Mentorship
π― Why Terraform?
Manual infrastructure creation leads to:
Configuration drift
Human errors
No version control
Terraform solves this using Infrastructure as Code (IaC).
πΉ What is Terraform?
Terraform is an open-source IaC tool by HashiCorp that:
Automates infrastructure provisioning
Works across clouds (AWS, Azure, GCP)
Uses declarative configuration
πΉ Terraform vs Manual Provisioning
| Manual | Terraform |
| Error-prone | Consistent |
| No history | Version-controlled |
| Hard to replicate | Repeatable |
πΉ Terraform Workflow
terraform init
terraform plan
terraform apply
terraform destroy
πΉ Terraform Configuration Files
| File | Purpose |
| main.tf | Resource definitions |
| variables.tf | Input variables |
| outputs.tf | Output values |
| provider.tf | Cloud provider |
| backend.tf | Remote state |
πΉ Terraform Provider Example
provider "aws" {
region = "us-east-1"
}
πΉ Create an EC2 Instance (Basic)
resource "aws_instance" "web" {
ami = "ami-0abcd1234"
instance_type = "t2.micro"
tags = {
Name = "Terraform-EC2"
}
}
πΉ Terraform Variables
variable "instance_type" {
default = "t2.micro"
}
Usage:
instance_type = var.instance_type
πΉ Terraform Output
output "instance_ip" {
value = aws_instance.web.public_ip
}
πΉ What is Terraform State?
State file (terraform.tfstate):
Maps real infra to code
Tracks resource changes
β οΈ Never edit manually.
πΉ Why Remote Backend (S3 + DynamoDB)?
Centralized state
Team collaboration
State locking
Backend Example
terraform {
backend "s3" {
bucket = "tf-state-bucket"
key = "prod/terraform.tfstate"
region = "us-east-1"
dynamodb_table = "terraform-lock"
}
}
πΉ What is State Locking?
Prevents:
Multiple users applying changes simultaneously
State corruption
DynamoDB handles locking.
πΉ Terraform Plan vs Apply
| plan | apply |
| Preview changes | Execute changes |
| Safe | Destructive |
πΉ Terraform Modules
Modules allow:
Reusability
Clean structure
Standardization
Simple Module Structure
modules/
βββ ec2/
βββ main.tf
βββ variables.tf
βββ outputs.tf
πΉ Terraform Best Practices
Use remote backend
Lock state
Use modules
Separate environments
Never commit state file
πΉ Terraform Destroy (Use Carefully)
terraform destroy
πΉ Real Production Scenario
Issue: Infra drift across environments
Fix: Terraform applied consistently
Result: Zero manual changes, stable infra
π― Interview Takeaways
Terraform is declarative
State is critical
Remote backend is mandatory
plan before apply
Modules are reusable