# 8. 🏗️ Terraform: Infrastructure as Code (IaC) from Scratch for DevOps Engineers

### 🎯 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

```bash
terraform init
terraform plan
terraform apply
terraform destroy
```

---

## 🔹 Terraform Configuration Files

| File | Purpose |
| --- | --- |
| [main.tf](http://main.tf) | Resource definitions |
| [variables.tf](http://variables.tf) | Input variables |
| [outputs.tf](http://outputs.tf) | Output values |
| [provider.tf](http://provider.tf) | Cloud provider |
| [backend.tf](http://backend.tf) | Remote state |

---

## 🔹 Terraform Provider Example

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

---

## 🔹 Create an EC2 Instance (Basic)

```bash
resource "aws_instance" "web" {
  ami           = "ami-0abcd1234"
  instance_type = "t2.micro"

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

---

## 🔹 Terraform Variables

```bash
variable "instance_type" {
  default = "t2.micro"
}
```

Usage:

```bash
instance_type = var.instance_type
```

---

## 🔹 Terraform Output

```bash
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

```bash
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

```bash
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)

```bash
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
