Setup Infrastructure as Code (IaC)
✅ Step 1: Install Terraform
Make sure Terraform is installed on your local machine:
terraform -v
If not installed, download it from terraform.io.
Install Terraform in WSL, not on Windows directly, if you're doing your DevOps work inside WSL.
✅ Why Install in WSL?
- Your scripts, AWS CLI config, Docker, and GitHub repo are all inside WSL.
- You’ll likely be running
terraform apply
,terraform init
from WSL. - It ensures filesystem paths, SSH keys, and AWS credentials are consistent.
✅ Step 2: Create Terraform Configuration Folder
mkdir ec2-terraform-demo && cd ec2-terraform-demo
✅ Step 3: Create Terraform Files
main.tf
provider "aws" {
region = "us-east-1"
}
resource "aws_key_pair" "demo_key" {
key_name = "demo-key"
public_key = file("~/.ssh/fresh_key.pub")
}
resource "aws_security_group" "demo_sg" {
name = "demo-sg"
description = "Allow SSH and HTTP"
ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
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"]
}
}
resource "aws_instance" "demo_instance" {
ami = "ami-053b0d53c279acc90"
instance_type = "t3.micro"
key_name = aws_key_pair.demo_key.key_name
vpc_security_group_ids = [aws_security_group.demo_sg.id]
associate_public_ip_address = false
tags = {
Name = "DemoInstance"
}
provisioner "remote-exec" {
inline = [
"sudo apt update -y",
"sudo apt install -y git docker.io docker-compose",
"sudo systemctl start docker",
"sudo systemctl enable docker",
"sudo usermod -aG docker ubuntu",
"cd /home/ubuntu",
"git clone https://github.com/arduino731/DevOps-Linux-System-Admin.git",
"cd DevOps-Linux-System-Admin",
"sudo docker-compose up -d"
]
connection {
type = "ssh"
user = "ubuntu"
private_key = file("~/.ssh/fresh_key.pem")
host = aws_eip.demo_eip.public_ip
}
}
}
resource "aws_eip" "demo_eip" {
domain = "vpc"
}
resource "aws_eip_association" "eip_assoc" {
instance_id = aws_instance.demo_instance.id
allocation_id = aws_eip.demo_eip.id
}
✅ Step 4: Initialize and Apply Terraform
terraform init
terraform apply
✅ Step 5: Setup AWS CLI
aws configure
aws s3 ls
✅ Final Deployment Script (deploy.sh)
#!/bin/bash
set -e
echo "[$(date)] Starting deployment..."
rsync -avz --exclude 'node_modules' --exclude 'aws' \
-e "ssh -i ~/.ssh/fresh_key.pem" \
./ ubuntu@ec2-YOUR-IP.compute-1.amazonaws.com:/home/ubuntu/app/DevOps-Linux-System-Admin
ssh -i ~/.ssh/fresh_key.pem ubuntu@ec2-YOUR-IP.compute-1.amazonaws.com << 'EOF'
echo "[$(date)] Restarting Docker containers..."
cd ~/app/DevOps-Linux-System-Admin
docker-compose down
docker-compose up -d --build
docker ps --filter "health=unhealthy" --format "⚠️ Unhealthy container: {{.Names}}"
EOF