πŸ‘ˆ

🧭 COMPLETE AWS EC2 HANDS-ON ROADMAP

πŸ§ͺ EC2 HANDS-ON – LAB 1

πŸ‘‰ Launch Your First EC2 Instance (Free Tier – SAFE)

🎯 Objective

You will:

  • Launch a Free Tier EC2 instance
  • Understand AMI, instance type, key pair, security group
  • Get a public IP

🧠 Before You Start (Very Important)

  • Login to Amazon Web Services Management Console
  • Make sure you are in ONE region (example: ap-south-1 (Mumbai))

πŸ‘‰ Region matters because:

  • EC2 runs inside a region
  • Free tier limits are per region

πŸ”Ή STEP 1: Go to EC2 Dashboard

  1. Login to AWS Console
  2. In the search bar, type: EC2
  3. Click EC2

πŸ“Œ You are now inside the EC2 service


πŸ”Ή STEP 2: Click β€œLaunch Instance”

  1. Click Launch Instance
  2. You will see a Launch Instance page

πŸ”Ή STEP 3: Name Your Instance

  • Instance name:

    ec2-hands-on-1
    

πŸ“Œ This is just a label to identify your server


πŸ”Ή STEP 4: Choose AMI (Operating System)

Select:

  • Amazon Linux 2023 AMI

πŸ“Œ Why?

  • Free tier eligible
  • Optimized for AWS
  • Secure and lightweight

βœ… Do NOT choose Ubuntu for now


πŸ”Ή STEP 5: Choose Instance Type

Select:

  • t2.micro

πŸ“Œ Why?

  • 1 vCPU
  • 1 GB RAM
  • FREE TIER ELIGIBLE

⚠️ Anything else = billing risk


πŸ”Ή STEP 6: Create Key Pair (VERY IMPORTANT)

Key pair = login password for your server

  1. Click Create new key pair

  2. Key pair name:

    ec2-key-hands-on
    
  3. Key pair type: RSA

  4. Private key format: .pem

  5. Click Create key pair

πŸ“Œ A .pem file will download ⚠️ DO NOT DELETE IT Without this, you cannot login


πŸ”Ή STEP 7: Configure Network Settings (Security Group)

Click Edit under Network settings

Inbound rules (ALLOW ACCESS):

TypePortSource
SSH22My IP
HTTP80Anywhere

πŸ“Œ Explanation:

  • SSH (22) β†’ Login to EC2
  • HTTP (80) β†’ Web server access
  • My IP β†’ Secure (only your system)
  • Anywhere β†’ Public website access

πŸ”Ή STEP 8: Storage (Leave Default)

  • 8 GiB (gp3) β†’ Leave as it is

πŸ“Œ Free tier allows up to 30 GB


πŸ”Ή STEP 9: Launch Instance

  1. Review everything
  2. Click Launch Instance
  3. Click View all instances

πŸ”Ή STEP 10: Verify Instance Status

Your instance state should be:

  • 🟑 Initializing
  • 🟒 Running

Click your instance and check:

  • Instance State β†’ Running
  • Public IPv4 address β†’ COPY IT

πŸ“Œ This IP is your server on the internet


βœ… TASK FOR YOU (DO THIS NOW)

βœ” Launch EC2 instance βœ” Instance state = Running βœ” You can see Public IPv4 address


Excellent πŸ‘ LAB 1 completed successfully βœ… Now we move to the next hands-on, exactly as promised.


πŸ§ͺ EC2 HANDS-ON – LAB 2

πŸ‘‰ Connect to EC2 using SSH

Image

Image


🎯 Objective of This Lab

You will:

  • Connect to your EC2 instance from your Windows laptop
  • Understand SSH, key pair, user, IP
  • Login successfully without fear or confusion

🧠 Important Concepts

Before doing steps, understand this:

πŸ”Ή What is SSH?

SSH (Secure Shell) is a secure way to:

  • Connect your laptop β†’ EC2 server
  • Run commands on the server

Think like this:

SSH = Remote control of your EC2 using text commands


πŸ”Ή What do we need for SSH?

We need 4 things:

  1. Public IP β†’ Address of your EC2
  2. Key pair (.pem file) β†’ Password (but more secure)
  3. Username β†’ Depends on OS
  4. SSH command

πŸ”Ή STEP 1: Open PowerShell (Windows)

  1. Press Windows key
  2. Type: PowerShell
  3. Open Windows PowerShell

πŸ“Œ Do NOT open CMD PowerShell supports SSH by default


πŸ”Ή STEP 2: Go to Folder Where .pem File Exists

Your key file name:

ec2-key-hands-on.pem

Usually it is in Downloads folder.

Run this command:

cd Downloads

πŸ“Œ Explanation:

  • cd = change directory
  • Downloads = folder name

To confirm file exists, run:

ls

πŸ“Œ ls shows list of files You should see:

ec2-key-hands-on.pem

πŸ”Ή STEP 3: Copy Your EC2 Public IP

  1. Go to EC2 Console
  2. Click your instance
  3. Copy Public IPv4 address

Example:

13.235.xxx.xxx

πŸ”Ή STEP 4: Understand the SSH Command (IMPORTANT)

SSH command format:

ssh -i keyfile.pem username@public-ip

Now replace values πŸ‘‡

PartValue
keyfileec2-key-hands-on.pem
usernameec2-user
public-ipyour EC2 IP

πŸ“Œ Why ec2-user? Because you selected Amazon Linux AMI


πŸ”Ή STEP 5: Connect to EC2 (RUN THIS)

ssh -i ec2-key-hands-on.pem ec2-user@YOUR_PUBLIC_IP

Example:

ssh -i ec2-key-hands-on.pem ec2-user@13.235.xxx.xxx

πŸ”Ή STEP 6: Type β€œyes” (First Time Only)

You will see:

Are you sure you want to continue connecting (yes/no)?

Type:

yes

Press Enter

πŸ“Œ This happens only once It means: β€œI trust this server”


πŸŽ‰ SUCCESS CHECK (VERY IMPORTANT)

If you see something like:

[ec2-user@ip-172-31-xx-xx ~]$

βœ… YOU ARE INSIDE EC2 SERVER

This means:

  • Your laptop β†’ connected to AWS server
  • SSH is working
  • Key pair is correct

πŸ” Verify You Are Really Inside EC2

Run:

whoami

Output should be:

ec2-user

Run:

pwd

Output:

/home/ec2-user

βœ… TASK FOR YOU (LAB 2)

βœ” Open PowerShell

βœ” SSH into EC2

βœ” See [ec2-user@...]$ prompt

βœ” Run whoami


πŸ”‘ What is a Key Pair in EC2?

A Key Pair is like a lock and key πŸ”

  • Public key β†’ Stored inside the EC2 instance (AWS keeps it)
  • Private key β†’ Downloaded by you (file like .pem or .ppk)

This key pair is used to log in securely to your EC2 instance.

πŸ‘‰ Without a key pair, you CANNOT login to EC2


🧭 When You Create a Key Pair – What Options You See

When you click Create new key pair, AWS shows 2 main options:

Image


1️⃣ Key Pair Type

You will see two options:

πŸ”Ή RSA (Most common βœ…)

  • Old but very stable
  • Supported everywhere
  • Default choice

πŸ‘‰ Use this if you are a beginner

πŸ”Ή ED25519

  • Newer & more secure
  • Faster
  • Not supported by some old systems

πŸ‘‰ Use this only if you clearly know you need it

βœ… Recommended for you: RSA


2️⃣ Private Key File Format (MOST IMPORTANT)

This is where people get confused πŸ‘‡

You will see two options:


πŸ”Ή .pem file (Linux / Mac / Git Bash)

Use this when:

  • EC2 OS is Amazon Linux / Ubuntu

  • You connect using:

    • Git Bash
    • MobaXterm
    • Mac Terminal
    • Linux Terminal

πŸ”Ή .ppk file (Windows – PuTTY)

Use this when:

  • You use PuTTY on Windows
  • You don’t want to convert .pem to .ppk

Used directly in PuTTY β†’ Auth β†’ Private key file


🧠 Very Important Rule (Remember This)

Your ToolChoose This
Git Bash / MobaXterm.pem
Mac / Linux Terminal.pem
PuTTY (Windows).ppk

πŸ‘‰ If confused β†’ Always choose .pem You can later convert .pem β†’ .ppk, but not easily the other way.


❗ IMPORTANT WARNINGS (Real-life mistakes)

⚠️ Download key only ONCE

  • AWS will never show it again
  • If you lose it β†’ You lose access

⚠️ Do NOT share your private key

  • Anyone with this file can access your server

⚠️ Do NOT upload key to GitHub

  • This is a serious security risk

🧠 Short Memory Trick

Linux server = .pem PuTTY user = .ppk


πŸ” What β€œKey Pair” Means Internally (Big Picture)

An EC2 key pair uses asymmetric encryption.

That means:

  • πŸ”‘ Public Key β†’ stored on the EC2 server
  • πŸ—οΈ Private Key β†’ stored ONLY with you
  • They work together, not separately

Think of it like:

Public key = Lock Private key = Only key that can open that lock


🧠 Step-by-Step: What Happens Internally

Image

When EC2 instance is launched:

  • The public key is copied into the server file:
~/.ssh/authorized_keys

This file lives inside the EC2 instance.

πŸ‘‰ This file decides who is allowed to log in.


🟒 You try to connect (SSH)

You run:

ssh -i mykey.pem ec2-user@<public-ip>

What happens internally:

  1. You say: β€œHey server, I want to login”
  2. Server says: β€œProve you are authorized”

🟒 Server sends a challenge πŸ”’

The EC2 server:

  • Creates a random encrypted message
  • Encrypts it using the public key
  • Sends it to your system

⚠️ Important:

  • Only the matching private key can decrypt it

🟒 Step 5: Your private key responds πŸ”“

Your computer:

  • Uses your private key
  • Decrypts the message
  • Sends the correct response back

🟒 Step 6: Server verifies and allows login βœ…

Server checks:

  • β€œDoes this response match what I expected?”

If YES:

  • Login allowed πŸŽ‰

If NO:

  • ❌ Permission denied

πŸ”„ Internal Flow (Very Simple)

You (Private Key)
        ↓
Decrypt challenge
        ↓
Send proof
        ↓
EC2 checks using Public Key
        ↓
Login allowed

πŸ” Why Password Is NOT Used

EC2 does NOT use passwords by default because:

❌ Passwords can be:

  • Brute-forced
  • Stolen
  • Guessed

βœ… Keys are:

  • Very long
  • Mathematically linked
  • Impossible to guess

πŸ”₯ What If Someone Gets Public Key?

Nothing happens.

βœ”οΈ Public key:

  • Can be shared
  • Is useless without private key

❌ Private key:

  • MUST be protected
  • Gives full access

🧨 What If You Lose the Private Key?

Internally:

  • Server has the public key
  • You don’t have the private key
  • Authentication fails forever ❌

Result:

  • You cannot login

  • You must:

    • Detach root volume
    • Attach to another EC2
    • Add a new public key manually

🧠 One-Line Summary (Interview Ready)

EC2 uses SSH key-based authentication where the public key is stored on the server and the private key proves the client’s identity without ever being sent over the network.


πŸ§ͺ Real-World Analogy

  • Public key β†’ Lock on your house
  • Private key β†’ Actual key in your pocket
  • SSH login β†’ Trying to open the door

πŸ§ͺ EC2 HANDS-ON – LAB 3

πŸ‘‰ Install Apache Web Server & Host Your First Website

Image


🎯 Objective of This Lab

You will:

  • Install Apache (httpd) on EC2
  • Start the web server
  • Host a simple web page
  • Access it using browser + public IP

🧠 Important Concept (Simple Words)

πŸ”Ή What is Apache?

Apache (httpd) is a web server.

Meaning:

  • It listens on port 80
  • When someone opens your IP in browser
  • Apache sends a web page

πŸ”Ή STEP 1: Update Your EC2 Server

Run this command:

sudo dnf update -y

πŸ“Œ Explanation:

  • sudo β†’ run command as admin (root)
  • dnf β†’ package manager (like Play Store)
  • update β†’ update system packages
  • -y β†’ auto-approve (no questions)

πŸ”Ή STEP 2: Install Apache (httpd)

Run:

sudo dnf install httpd -y

πŸ“Œ Explanation:

  • install β†’ install software
  • httpd β†’ Apache web server package

πŸ”Ή STEP 3: Start Apache Server

sudo systemctl start httpd

πŸ“Œ Explanation:

  • systemctl β†’ service manager
  • start β†’ start service
  • httpd β†’ Apache service

πŸ”Ή STEP 4: Enable Apache on Boot (VERY IMPORTANT)

sudo systemctl enable httpd

πŸ“Œ Why?

  • If EC2 restarts
  • Apache starts automatically

πŸ”Ή STEP 5: Check Apache Status

sudo systemctl status httpd

You should see:

Active: active (running)

Press:

q

to exit status screen


πŸ”Ή STEP 6: Test in Browser (BIG MOMENT πŸŽ‰)

  1. Copy your EC2 Public IP
  2. Open browser
  3. Paste:
http://YOUR_PUBLIC_IP

Expected Result:

🟒 Apache Test Page

βœ… This means:

  • EC2 is running
  • Apache is working
  • Security group allows HTTP (port 80)

πŸ”Ή STEP 7: Create Your Own Web Page

Apache default folder:

/var/www/html

Go to folder:

cd /var/www/html

πŸ”Ή STEP 8: Create HTML File

sudo nano index.html

πŸ“Œ nano = simple text editor

Paste this:

<!DOCTYPE html>
<html>
<head>
  <title>My First EC2 Website</title>
</head>
<body>
  <h1>Hello from EC2 πŸš€</h1>
  <p>Apache Web Server is working!</p>
</body>
</html>

Save & Exit:

  • Press CTRL + X
  • Press Y
  • Press Enter

πŸ”Ή STEP 9: Refresh Browser

Open again:

http://YOUR_PUBLIC_IP

πŸŽ‰ You should see your own website


πŸ›‘ COMMON ISSUE CHECK

If page does not open:

  • Check Security Group β†’ HTTP (80) allowed
  • Instance state = Running
  • Apache status = active

βœ… TASK FOR YOU (LAB 3)

βœ” Apache installed βœ” Apache running βœ” Custom HTML page created βœ” Website opens using public IP


πŸ§ͺ EC2 HANDS-ON – LAB 4

πŸ‘‰ Elastic IP (Static Public IP) – No More IP Changes

Image


🎯 Objective of This Lab

You will:

  • Understand why public IP changes
  • Create an Elastic IP (EIP)
  • Attach it to your EC2 instance
  • Access your website using a fixed IP

🧠 Why Public IP Changes? (Simple Explanation)

Because the public IP is temporary unless you reserve it.

  • AWS gives you a temporary public IP by default.

  • When the instance stops and restarts, that IP is taken back by AWS.

❌ Bad for:

  • Websites
  • APIs
  • Domain mapping

🚨 IMPORTANT RULE (Remember This)

|Action | Public IP| |--- |---| |Reboot EC2 | ❌ Does NOT change| |Stop EC2 | βœ… Changes| |Terminate EC2 | ❌ Instance gone| |Start EC2 | βœ… New IP|


πŸ’° Cost: πŸ‘‰ ~$0.005 per hour per Elastic IP

🧠 What is Elastic IP?

Elastic IP (EIP) is:

  • A static public IPv4 address
  • Belongs to your AWS account
  • You can attach/detach to EC2

Think like:

Elastic IP = Permanent phone number πŸ“± Public IP = Temporary number


⚠️ Cost Warning (IMPORTANT)

  • Free when attached to running EC2

  • Charged if:

    • Not attached
    • Instance stopped

πŸ‘‰ We will keep it attached


πŸ”Ή STEP 1: Go to Elastic IPs

  1. Open EC2 Console
  2. Left menu β†’ Elastic IPs
  3. Click Allocate Elastic IP address

πŸ”Ή STEP 2: Allocate Elastic IP

  • Network border group β†’ Leave default
  • Click Allocate

You will now see a new Elastic IP


πŸ”Ή STEP 3: Associate Elastic IP to EC2

  1. Select Elastic IP
  2. Click Actions β†’ Associate Elastic IP
  3. Resource type β†’ Instance
  4. Instance β†’ select ec2-hands-on-1
  5. Click Associate

πŸ”Ή STEP 4: Verify Association

  • Elastic IP shows:

    • Instance ID
    • Private IP

Your EC2 now has:

  • Static public IP

πŸ”Ή STEP 5: Test Website Using Elastic IP

Open browser:

http://ELASTIC_IP

🟒 Your website should load


πŸ”Ή STEP 6: Confirm IP Stability (Understanding)

If you:

  • Restart EC2 ❌ (DON’T DO NOW)
  • Elastic IP will NOT change

πŸ›‘ IMPORTANT RULE

If you ever:

  • Terminate EC2 πŸ‘‰ First release Elastic IP Otherwise AWS will charge

βœ… TASK FOR YOU (LAB 4)

βœ” Elastic IP allocated βœ” Elastic IP associated to EC2 βœ” Website opens using Elastic IP


πŸ§ͺ EC2 HANDS-ON – LAB 5

πŸ‘‰ Attach a Domain to EC2 using Route 53 (Real-World Hosting)

Image


🎯 Objective of This Lab

You will:

  • Understand DNS & Domain flow
  • Create a Hosted Zone in Route 53
  • Map your Elastic IP β†’ Domain
  • Open your website using a domain name πŸŽ‰

🧠 First: Understand the Flow (VERY IMPORTANT)

When someone types:

www.example.com

What happens?

  1. Browser asks DNS
  2. DNS replies β†’ Elastic IP
  3. Elastic IP points β†’ EC2
  4. Apache sends the website

πŸ‘‰ Route 53 = DNS service


🧠 What is Route 53?

Amazon Route 53 is:

  • AWS DNS service
  • Converts domain β†’ IP address
  • Highly available & fast

⚠️ IMPORTANT NOTE (READ CAREFULLY)

There are TWO CASES:

βœ… Case 1: You already bought a domain

(from GoDaddy / Namecheap / Route 53)

β†’ Continue with this lab

❌ Case 2: You don’t have a domain yet

β†’ You can still practice using a fake domain name (no website will open publicly, but concept is same)

I’ll explain both safely.


πŸ”Ή STEP 1: Open Route 53

  1. AWS Console β†’ search Route 53
  2. Open Route 53
  3. Click Hosted zones
  4. Click Create hosted zone

πŸ”Ή STEP 2: Create Hosted Zone

Fill details:

  • Domain name Example:

    devcloudpractice.com
    
  • Type β†’ Public Hosted Zone

Click Create hosted zone

πŸ“Œ Hosted Zone = DNS control panel for your domain


πŸ”Ή STEP 3: Understand Name Servers (CRITICAL)

After creation, you’ll see 4 NS records, like:

ns-123.awsdns-45.com
ns-678.awsdns-90.net
...

πŸ“Œ These are AWS DNS servers


πŸ”Ή STEP 4: Update Name Servers (Only if Domain Bought Outside AWS)

If your domain is from:

  • GoDaddy
  • Namecheap
  • Hostinger

Go to domain provider:

  1. Open DNS / Nameserver settings
  2. Replace existing name servers
  3. Paste Route 53 name servers
  4. Save

⏳ DNS propagation: 5–30 minutes (sometimes 24 hrs)

⚠️ If domain bought from Route 53 β†’ skip this step


πŸ”Ή STEP 5: Create A Record (Domain β†’ EC2)

Inside Hosted Zone:

  1. Click Create record

  2. Record type β†’ A

  3. Record name:

    • Leave empty β†’ root domain (example.com)
  4. Value:

    • Paste Elastic IP
  5. TTL β†’ default

  6. Click Create records

πŸ“Œ A record = maps domain β†’ IP


πŸ”Ή STEP 6: (Optional) Create www Record

Create another record:

  • Record name:

    www
    
  • Type β†’ A

  • Value β†’ Elastic IP

This enables:

www.example.com

πŸ”Ή STEP 7: Test Your Domain πŸŽ‰

Open browser:

http://yourdomain.com

or

http://www.yourdomain.com

🟒 Your EC2 website should load


🧠 Real-World Knowledge (Interview Ready)

βœ” Route 53 does not host websites βœ” It only does DNS resolution βœ” EC2 + Apache hosts the website βœ” Elastic IP ensures static mapping


πŸ›‘ Common Issues Checklist

IssueFix
Site not openingWait DNS propagation
IP wrongCheck Elastic IP
Apache downsystemctl status httpd
HTTP blockedSecurity Group port 80

βœ… TASK FOR YOU (LAB 5)

βœ” Hosted Zone created βœ” A record added βœ” Domain mapped to Elastic IP


πŸ” EC2 Security Group – SSH, Ports, and IP Access


1️⃣ What is a Security Group in EC2?

  • A Security Group is a virtual firewall

  • It controls:

    • Who can reach your EC2 instance
    • On which port
  • It works at network level (before login)

πŸ‘‰ If traffic is not allowed by Security Group β†’ EC2 never receives it.


2️⃣ What does 0.0.0.0/0 mean?

0.0.0.0/0 = ANY IP address on the internet

⚠️ This means publicly open to the world.


3️⃣ What does β€œMy IP” mean?

When you select My IP, AWS:

  • Detects your current public internet IP
  • Sets the rule as:
x.x.x.x/32

/32 means:

  • Only ONE exact IP
  • Only your current network

πŸ‘‰ This is secure and recommended.


4️⃣ Understanding the 3 Important Ports

πŸ” Port 22 – SSH

Used for:

  • Remote login to EC2
  • Full server control (admin access)

What SSH gives:

  • File access
  • Command execution
  • Full OS control

πŸ‘‰ This is the most sensitive port


🌐 Port 80 – HTTP

Used for:

  • Website access via browser
  • Public web traffic

What HTTP gives:

  • Only what your application exposes
  • No OS access
  • No command execution

πŸ‘‰ Designed to be public


βš™οΈ Port 8080 – Application Port

Used for:

  • Spring Boot
  • Node.js
  • Test applications

Access level:

  • Application only
  • Not OS-level

πŸ‘‰ Safe for testing, risky if admin APIs are exposed


5️⃣ Why ONLY SSH is dangerous when open to 0.0.0.0/0

Key reason:

SSH provides full administrative access to the server

Comparison:

PortAccess TypeRisk
22 (SSH)Full OS controlπŸ”₯ Very High
80 (HTTP)Web content only🟒 Low
8080App-level access🟑 Medium

πŸ‘‰ Admin access should never be public


6️⃣ What happens if SSH is set to 0.0.0.0/0

Important clarification:

❌ Anyone CANNOT login without .pem key

βœ… Anyone CAN try to connect

What attackers can do:

  • Scan your public IP

  • Detect open port 22

  • Attempt:

    • Usernames
    • Stolen keys
    • Brute-force attacks

Even if they fail:

  • Continuous attack attempts
  • Log flooding
  • Resource usage
  • High security risk

7️⃣ Two Levels of EC2 Security (Very Important)

Level 1️⃣: Security Group (Network Gate)

  • Controls who can reach the port

Level 2️⃣: SSH Authentication (Login Lock)

  • Requires:

    • Correct username
    • Correct private key (.pem)

πŸ‘‰ 0.0.0.0/0 opens the gate, not the lock


8️⃣ Why .pem key is still required

  • EC2 uses key-based authentication
  • Password login is disabled by default
  • Private key is never sent over the network

So:

  • ❌ No .pem β†’ No login
  • ❌ Even AWS can’t login without it

PortSourceStatus
22 (SSH)My IPβœ… Secure
80 (HTTP)0.0.0.0/0βœ… Required
80800.0.0.0/0 (temporary)⚠️ OK for testing

πŸ” Golden Security Rule (Must Remember)

Never expose administrative access (SSH) to the public internet.

  • SSH β†’ restrict to your IP
  • HTTP/HTTPS β†’ public
  • App ports β†’ open only if needed

🎯 Interview-Ready One-Line Answer

Opening SSH to 0.0.0.0/0 allows anyone on the internet to attempt connections, increasing attack risk. SSH must be restricted to trusted IPs, while HTTP is designed for public access.


πŸ§ͺ EC2 HANDS-ON – LAB 6

πŸ‘‰ Security Groups (Inbound & Outbound Rules – Deep Hands-On)

Image


🎯 Objective of LAB 6

By the end of this lab, you will:

  • Create & modify Security Group rules
  • Understand Inbound vs Outbound
  • Prove that Security Groups are STATEFUL
  • Be able to explain this confidently in interviews

🧠 FIRST: What is a Security Group? (Very Simple)

A Security Group (SG) is:

  • A virtual firewall
  • Controls who can access your EC2
  • Works at instance level

Think like this:

Security Group = Security guard at the door πŸšͺ Only allowed people can enter


🧠 IMPORTANT RULE (MEMORIZE)

❗ Security Groups:

  • βœ… Allow rules only
  • ❌ No deny rules
  • βœ… Are STATEFUL

We will prove this practically.


πŸ”Ή STEP 1: Open Your EC2 Security Group

  1. AWS Console β†’ EC2
  2. Click Instances
  3. Select your instance ec2-hands-on-1
  4. Go to Security tab
  5. Click the Security group name

You are now inside Security Group settings


πŸ”Ή STEP 2: Understand Existing Inbound Rules

You should already see something like:

TypePortSource
SSH22My IP
HTTP80Anywhere

What this means:

  • SSH β†’ You can connect from your laptop
  • HTTP β†’ Anyone can open your website

πŸ”Ή STEP 3: TEST 1 – Remove HTTP Access (Hands-On Proof)

❌ Remove HTTP Rule

  1. Click Edit inbound rules
  2. ❌ Delete HTTP (port 80)
  3. Click Save rules

πŸ” TEST IN BROWSER

Open:

http://ELASTIC_IP

Expected Result:

❌ Website WILL NOT OPEN

βœ… This proves:

  • Security Group controls traffic
  • Port 80 is required for web access

πŸ”Ή STEP 4: Add HTTP Rule Back

  1. Edit inbound rules
  2. Add rule:
SettingValue
TypeHTTP
Port80
SourceAnywhere (0.0.0.0/0)
  1. Save rules

πŸ” Refresh browser

Result:

🟒 Website opens again


πŸ”Ή STEP 5: TEST 2 – Change SSH Source (IMPORTANT)

❌ Break SSH Access (on purpose)

  1. Edit inbound rules
  2. Change SSH source from:
My IP

to:

0.0.0.0/0
  1. Save

πŸ“Œ Meaning:

  • Anyone on internet can try SSH (❌ unsafe)

⚠️ We will fix it later


πŸ”Ή STEP 6: Understand INBOUND vs OUTBOUND

Inbound Rules

πŸ‘‰ Who can come IN to EC2 Examples:

  • SSH (22)
  • HTTP (80)

Outbound Rules

πŸ‘‰ Where EC2 can go OUT

Default outbound rule:

All traffic β†’ 0.0.0.0/0

πŸ“Œ Means:

  • EC2 can access internet
  • Install updates
  • Download packages

πŸ”Ή STEP 7: STATEFUL PROOF (VERY IMPORTANT)

Security Groups are STATEFUL.

What does that mean?

If:

  • Inbound request is allowed Then:
  • Response is automatically allowed (No outbound rule needed)

πŸ“Œ Example:

  • Browser β†’ EC2 (HTTP allowed)
  • EC2 β†’ Browser (response allowed automatically)

πŸ’‘ This is interview GOLD


πŸ”Ή STEP 8: FIX SECURITY (BEST PRACTICE)

Now make SSH secure again πŸ‘‡

  1. Edit inbound rules
  2. Change SSH source back to:
My IP
  1. Save

βœ… Your EC2 is secure again


🧠 INTERVIEW-READY ANSWER (MEMORIZE)

Security Group is a stateful virtual firewall that controls inbound and outbound traffic at the EC2 instance level. It supports only allow rules, and responses to allowed inbound traffic are automatically permitted.


βœ… LAB 6 TASK CHECKLIST

βœ” Removed HTTP and tested βœ” Added HTTP and tested βœ” Understood inbound vs outbound βœ” Proved STATEFUL behavior βœ” Secured SSH again


πŸ§ͺ EC2 HANDS-ON – LAB 7

πŸ‘‰ Network ACL (NACL) vs Security Group (Hands-On + Deep Clarity)

Image


🎯 Objective of LAB 7

By the end of this lab, you will:

  • Create & modify a Network ACL
  • See how it works at subnet level
  • PROVE it is STATELESS
  • Understand NACL vs Security Group (interview-ready)

🧠 FIRST: What is a Network ACL? (Simple Words)

A Network ACL (NACL) is:

  • A firewall for a subnet
  • Works before traffic reaches EC2
  • Applies to ALL instances in that subnet

Think like:

NACL = Security gate at society entrance 🏒 Security Group = Guard at each flat πŸšͺ


🧠 VERY IMPORTANT RULES (MEMORIZE)

FeatureNACL
LevelSubnet
RulesAllow + Deny
NatureSTATELESS
OrderRule number (100, 110…)
DefaultAllow all

πŸ”Ή STEP 1: Open Network ACLs

  1. AWS Console β†’ VPC
  2. Left menu β†’ Network ACLs
  3. You will see a default NACL

πŸ”Ή STEP 2: Identify Your Subnet

  1. Go to EC2 β†’ Instances
  2. Click your instance
  3. Note Subnet ID

πŸ“Œ We will apply NACL to this subnet


πŸ”Ή STEP 3: Create Custom NACL

  1. VPC β†’ Network ACLs

  2. Click Create network ACL

  3. Name:

    ec2-hands-on-nacl
    
  4. Select your VPC

  5. Click Create


πŸ”Ή STEP 4: Associate NACL with Subnet

  1. Select your new NACL
  2. Go to Subnet associations
  3. Click Edit subnet associations
  4. Select your EC2 subnet
  5. Save

⚠️ This NACL now controls traffic for your EC2


πŸ”Ή STEP 5: BLOCK HTTP Using NACL (Hands-On Proof)

Inbound Rule – DENY HTTP

  1. Select Inbound rules
  2. Click Edit inbound rules
  3. Add rule:
Rule #TypePortSourceAction
100HTTP800.0.0.0/0DENY
  1. Save

πŸ” TEST IN BROWSER

Open:

http://ELASTIC_IP

❌ Website WILL NOT OPEN

πŸ“Œ Even though:

  • Security Group allows HTTP
  • NACL denies it

πŸ‘‰ NACL blocks first


πŸ”Ή STEP 6: ALLOW HTTP Again

Add ALLOW rule with higher priority:

Rule #TypePortSourceAction
90HTTP800.0.0.0/0ALLOW

πŸ“Œ Rule 90 runs before 100

πŸ” Refresh browser β†’ 🟒 Works


πŸ”Ή STEP 7: PROVE STATELESS BEHAVIOR (IMPORTANT)

❌ Remove Outbound Rule

  1. Go to Outbound rules
  2. Delete rule:
ALLOW ALL (0.0.0.0/0)
  1. Save

πŸ” Test Website Again

❌ Website WILL NOT LOAD

πŸ“Œ Why?

  • Inbound allowed
  • Outbound response blocked

πŸ‘‰ This PROVES NACL is STATELESS


πŸ”Ή STEP 8: FIX OUTBOUND RULE (IMPORTANT)

Add outbound rule:

Rule #TypePortDestinationAction
100HTTP800.0.0.0/0ALLOW

Also add:

Rule #TypePortDestinationAction
110HTTPS4430.0.0.0/0ALLOW

Save


πŸ”Ή STEP 9: FINAL COMPARISON (INTERVIEW TABLE)

FeatureSecurity GroupNACL
LevelInstanceSubnet
RulesAllow onlyAllow + Deny
NatureStatefulStateless
Rule OrderNo orderNumber based
ScopeSpecific EC2All in subnet

🧠 INTERVIEW-READY ANSWER

Security Groups act as a stateful firewall at the instance level allowing only permitted traffic, whereas Network ACLs operate at the subnet level, are stateless, and support both allow and deny rules evaluated in order.


⚠️ CLEANUP (VERY IMPORTANT)

To avoid confusion later:

  • Either restore default NACL
  • Or keep both inbound & outbound properly allowed

βœ… LAB 7 TASK CHECKLIST

βœ” Created custom NACL βœ” Associated subnet βœ” Denied & allowed HTTP βœ” Proved stateless behavior βœ” Understood SG vs NACL clearly


πŸ§ͺ EC2 HANDS-ON – LAB 8

πŸ‘‰ EC2 Key Pairs (Create, Use, Delete & Recover Access)

Image


🎯 Objective of LAB 8

You will:

  • Understand what a key pair really is
  • Create & attach new key pairs
  • Know what happens if key is deleted
  • Learn key recovery concept (very important)

🧠 FIRST: What is an EC2 Key Pair?

A Key Pair has:

  • Public key β†’ Stored in EC2
  • Private key (.pem) β†’ Stored on your laptop

Think like:

Lock (public key) is on server πŸ”’ Key (private key) is with you πŸ”‘

AWS never stores private key.


πŸ”Ή STEP 1: View Existing Key Pair

  1. EC2 Console β†’ Key Pairs
  2. You will see:
ec2-key-hands-on

πŸ“Œ AWS only shows key name, not the file


πŸ”Ή STEP 2: Create a SECOND Key Pair

  1. Click Create key pair
  2. Name:
ec2-key-backup
  1. Type: RSA
  2. Format: .pem
  3. Create & download

πŸ“Œ This is for learning purpose


πŸ”Ή STEP 3: Understand a CRITICAL RULE

❗ You cannot directly change key pair of:

  • Running instance
  • Stopped instance

Key pair is:

  • Injected at launch time

πŸ”Ή STEP 4: What Happens If Key is Deleted? (Concept)

Scenario:

  • .pem file deleted from laptop ❌
  • EC2 still running

Result:

❌ You are LOCKED OUT

AWS cannot recover it


πŸ”Ή STEP 5: HOW TO RECOVER ACCESS (IMPORTANT CONCEPT)

There are 3 real-world recovery methods:


🟒 Method 1: EC2 Instance Connect (AWS Linux only)

  • Works only if:

    • Instance supports it
    • Port 22 allowed
  • Temporary access


🟒 Method 2: Detach Root Volume (MOST COMMON)

Steps (conceptual):

  1. Stop instance
  2. Detach root EBS
  3. Attach it to another EC2
  4. Add new public key to:
~/.ssh/authorized_keys
  1. Reattach volume
  2. Start instance

πŸ“Œ Very important interview topic


🟒 Method 3: Session Manager (BEST PRACTICE)

  • Uses IAM Role
  • No SSH, no key pair
  • Secure & auditable

We’ll do this hands-on later


πŸ”Ή STEP 6: BEST PRACTICES (MEMORIZE)

βœ” Always keep backup key βœ” Use IAM Roles + Session Manager βœ” Never share .pem βœ” Restrict SSH source βœ” Rotate keys in production


🧠 INTERVIEW-READY ANSWER

An EC2 key pair consists of a public key stored on the instance and a private key held by the user. AWS does not store the private key, and if it is lost, access must be recovered through volume attachment or Session Manager.


πŸ›‘ DO NOT TRY KEY RECOVERY NOW

We will do it safely in advanced labs.


βœ… LAB 8 TASK CHECKLIST

βœ” Understood key pair concept βœ” Created backup key βœ” Learned recovery methods βœ” Understood best practices


πŸ§ͺ EC2 HANDS-ON – LAB 9

πŸ‘‰ EC2 User Data (Automatic Setup at Launch)

Image


🎯 Objective of LAB 9

By the end of this lab, you will:

  • Understand what User Data is
  • Use User Data to auto-install Apache
  • Deploy a website WITHOUT SSH
  • Learn cloud-init concept (interview topic)

🧠 FIRST: What is EC2 User Data? (Very Simple)

User Data is:

  • A script that runs only once
  • Runs when EC2 starts for the first time
  • Used for automation

Think like:

User Data = Auto-setup instructions for EC2 🧠

Example:

  • Install Apache
  • Start service
  • Create website
  • Configure app

🧠 VERY IMPORTANT RULES (MEMORIZE)

❗ User Data:

  • Runs only at first launch
  • Runs as root user
  • Uses cloud-init
  • Best for bootstrapping

πŸ”Ή WHAT WE WILL DO (PLAN)

We will:

  1. Launch NEW EC2 instance
  2. Add User Data script
  3. Apache installs automatically
  4. Website works without SSH

πŸ”Ή STEP 1: Launch a NEW EC2 Instance

Go to: EC2 β†’ Instances β†’ Launch instance

Instance name:

ec2-userdata-demo

πŸ”Ή STEP 2: Choose AMI & Instance Type

  • AMI β†’ Amazon Linux 2023
  • Instance type β†’ t2.micro (Free tier)

πŸ”Ή STEP 3: Select Key Pair

Choose:

ec2-key-hands-on

(We won’t SSH, but AWS requires it)


πŸ”Ή STEP 4: Network & Security Group

Inbound rules:

TypePortSource
HTTP80Anywhere
SSH22My IP

πŸ”Ή STEP 5: ADD USER DATA (MOST IMPORTANT)

Scroll down β†’ Advanced details

Find:

πŸ‘‰ User data

Paste EXACTLY this:

#!/bin/bash
dnf update -y
dnf install httpd -y
systemctl start httpd
systemctl enable httpd

echo "<h1>Hello from EC2 User Data πŸš€</h1>" > /var/www/html/index.html

🧠 EXPLAIN SCRIPT LINE BY LINE (IMPORTANT)

#!/bin/bash

➑ Tells EC2: β€œThis is a Linux shell script”

dnf update -y

➑ Updates system packages

dnf install httpd -y

➑ Installs Apache web server

systemctl start httpd

➑ Starts Apache

systemctl enable httpd

➑ Starts Apache on reboot

echo "<h1>Hello from EC2 User Data πŸš€</h1>" > /var/www/html/index.html

➑ Creates website homepage automatically


πŸ”Ή STEP 6: Launch Instance

Click Launch instance

Wait until: 🟒 Instance state β†’ Running


πŸ”Ή STEP 7: Test WITHOUT SSH (BIG MOMENT πŸŽ‰)

  1. Copy Public IP
  2. Open browser:
http://PUBLIC_IP

Expected Output:

Hello from EC2 User Data πŸš€

βœ… Apache installed βœ… Website deployed βœ… No manual work


πŸ”Ή STEP 8: Verify User Data Ran (Optional SSH)

If you want to check logs:

sudo cat /var/log/cloud-init-output.log

πŸ“Œ Shows user data execution logs


🧠 INTERVIEW-READY ANSWER

EC2 User Data is a cloud-init based mechanism that allows running scripts at instance launch to automate configuration such as installing software and starting services. It runs only once at first boot.


⚠️ COMMON MISTAKES (VERY IMPORTANT)

❌ Forget #!/bin/bash ❌ Wrong indentation ❌ Expecting script to run again after reboot ❌ Missing HTTP rule in SG


βœ… LAB 9 TASK CHECKLIST

  • βœ” New EC2 launched
  • βœ” User Data added
  • βœ” Apache auto-installed
  • βœ” Website works without SSH
  • βœ” Understood automation concept

πŸ§ͺ EC2 HANDS-ON – LAB 10

πŸ‘‰ EC2 Instance Lifecycle (Start, Stop, Reboot, Terminate)

Image


🎯 Objective of LAB 10

You will:

  • Perform Start / Stop / Reboot / Terminate
  • Understand what happens to IP, storage, billing
  • Learn when to use each action
  • Be interview-ready

🧠 FIRST: EC2 Lifecycle States (Simple)

An EC2 instance can be in:

StateMeaning
PendingStarting
RunningActive
StoppedPowered off
TerminatedDeleted forever

πŸ”Ή STEP 1: Identify Two Instances

You should have:

  1. ec2-hands-on-1 (Elastic IP attached)
  2. ec2-userdata-demo

We will safely test lifecycle on ec2-userdata-demo


πŸ”Ή STEP 2: STOP the Instance

  1. EC2 β†’ Instances
  2. Select ec2-userdata-demo
  3. Instance state β†’ Stop
  4. Confirm

πŸ” What Happens When STOP?

ItemResult
InstanceOFF
Billing❌ No compute cost
EBS rootβœ… Preserved
Public IP❌ Released
Elastic IP❌ Not attached

πŸ”Ή STEP 3: START the Instance Again

  1. Select instance
  2. Instance state β†’ Start

Wait β†’ Running


πŸ” Check Public IP

  • Public IP will be NEW
  • Website still works (Apache already installed)

πŸ“Œ This proves:

  • Data remains
  • Public IP changes

πŸ”Ή STEP 4: REBOOT the Instance

  1. Select instance
  2. Instance state β†’ Reboot

πŸ” What Happens When REBOOT?

ItemResult
OSRestarts
Public IPβœ… Same
Dataβœ… Safe
Billingβœ… Continues

πŸ“Œ Reboot = Restart laptop


πŸ”Ή STEP 5: TERMINATE the Instance (IMPORTANT)

⚠️ THIS IS DESTRUCTIVE

  1. Select ec2-userdata-demo
  2. Instance state β†’ Terminate
  3. Confirm

πŸ” What Happens When TERMINATE?

ItemResult
Instance❌ Deleted
EBS root❌ Deleted
Public IP❌ Gone
Recovery❌ Impossible

πŸ“Œ Terminate = Delete forever


🧠 VERY IMPORTANT INTERVIEW POINTS

  • Stop β†’ Save money
  • Start β†’ New public IP
  • Reboot β†’ Same IP
  • Terminate β†’ Data lost

🧠 INTERVIEW-READY ANSWER

Stopping an EC2 instance halts compute billing while preserving EBS volumes, whereas terminating an instance permanently deletes the instance and associated root volume, making recovery impossible.


⚠️ COST BEST PRACTICES

  • Stop unused instances
  • Use Elastic IP for static access
  • Terminate unused test EC2s
  • Monitor free tier usage

βœ… LAB 10 TASK CHECKLIST

  • Stopped instance
  • Started instance
  • Rebooted instance
  • Terminated test instance
  • Understood lifecycle fully

πŸ§ͺ EC2 HANDS-ON – LAB 11

πŸ‘‰ EBS Volumes (Attach, Mount, Detach & Resize)

Image


🎯 Objective of LAB 11

By the end of this lab, you will:

  • Understand what EBS is
  • Create an extra EBS volume
  • Attach it to EC2
  • Mount it inside Linux
  • Resize it safely
  • Be interview-ready

🧠 FIRST: What is EBS? (Simple Words)

EBS (Elastic Block Store) is:

  • A virtual hard disk
  • Used by EC2
  • Persistent storage

Think like:

EC2 = Laptop πŸ’» EBS = Hard disk πŸ’Ύ

Even if EC2 stops β†’ data stays.


🧠 IMPORTANT TYPES (FOR NOW)

We’ll use:

  • gp3 (General Purpose SSD)

πŸ“Œ Free tier friendly πŸ“Œ Balanced performance


πŸ”Ή STEP 1: Identify Your EC2 Instance

Use:

ec2-hands-on-1

⚠️ Do NOT use terminated instance


πŸ”Ή STEP 2: Create a NEW EBS Volume

  1. AWS Console β†’ EC2
  2. Left menu β†’ Volumes
  3. Click Create volume

Fill details:

  • Volume type β†’ gp3
  • Size β†’ 5 GiB
  • Availability Zone β†’ SAME as EC2
  • Name:
ebs-hands-on-1

Click Create volume

πŸ“Œ AZ must match EC2 AZ


πŸ”Ή STEP 3: Attach EBS Volume to EC2

  1. Select volume ebs-hands-on-1
  2. Actions β†’ Attach volume
  3. Instance β†’ ec2-hands-on-1
  4. Device β†’ /dev/xvdf
  5. Attach

πŸ”Ή STEP 4: Connect to EC2 (SSH)

ssh -i ec2-key-hands-on.pem ec2-user@ELASTIC_IP

πŸ”Ή STEP 5: Check Disk is Attached

Run:

lsblk

πŸ“Œ Explanation:

  • lsblk β†’ list block devices (disks)

You will see:

  • xvda β†’ root disk
  • xvdf β†’ new EBS (no mount yet)

πŸ”Ή STEP 6: Format the New Volume

sudo mkfs -t xfs /dev/xvdf

πŸ“Œ Explanation:

  • mkfs β†’ make filesystem
  • xfs β†’ Linux filesystem
  • /dev/xvdf β†’ new disk

⚠️ Formatting erases data (safe now)


πŸ”Ή STEP 7: Create Mount Directory

Mounting an EBS volume is the process of making an attached storage volume accessible to the operating system at a specific directory path.

sudo mkdir /data

πŸ“Œ /data = folder to access EBS

❓ Why mounting is required?

Because:

  • EC2 OS doesn’t know where to store data
  • EBS is just a block device
  • OS needs a mount point (folder)

πŸ” What happens if you DON’T mount?

  • Volume is attached βœ”
  • OS cannot read/write ❌
  • Storage is wasted

πŸ”Ή STEP 8: Mount the Volume

sudo mount /dev/xvdf /data

πŸ”Ή STEP 9: Verify Mount

df -h

πŸ“Œ You should see /data mounted


πŸ”Ή STEP 10: Make Mount Persistent (IMPORTANT)

Open fstab:

sudo nano /etc/fstab

Add line at bottom:

/dev/xvdf /data xfs defaults,nofail 0 2

Save & exit:

  • CTRL + X β†’ Y β†’ Enter

πŸ“Œ This ensures mount survives reboot


πŸ”Ή STEP 11: Resize EBS Volume (Hands-On)

Increase volume size

  1. EC2 β†’ Volumes
  2. Select ebs-hands-on-1
  3. Actions β†’ Modify volume
  4. Change size:
5 β†’ 10 GiB
  1. Save

Extend filesystem (inside EC2)

sudo xfs_growfs /data

πŸ“Œ Expands filesystem to new size

Verify:

df -h

🧠 VERY IMPORTANT INTERVIEW POINTS

βœ” EBS is AZ-specific βœ” EBS is persistent βœ” Can attach/detach βœ” Can resize without downtime βœ” Root volume is also EBS


🧠 INTERVIEW-READY ANSWER

Amazon EBS is a persistent block storage service designed for EC2 instances. It provides durable storage that can be attached, detached, resized, and snapshotted independently of the instance lifecycle.


⚠️ COMMON MISTAKES

❌ Different AZ for volume ❌ Forgetting filesystem resize ❌ Not updating /etc/fstab ❌ Formatting wrong disk


βœ… LAB 11 TASK CHECKLIST

βœ” Created EBS volume βœ” Attached to EC2 βœ” Formatted & mounted βœ” Made persistent βœ” Resized volume


πŸ§ͺ EC2 HANDS-ON – LAB 12

πŸ‘‰ EBS Snapshots & Restore (Backup & Disaster Recovery)

Image


🎯 Objective of LAB 12

By the end of this lab, you will:

  • Create an EBS snapshot (backup)
  • Restore a new volume from snapshot
  • Attach it to EC2
  • Prove data recovery
  • Understand real-world backup strategy

🧠 FIRST: What is an EBS Snapshot? (Simple)

An EBS Snapshot is:

  • A backup of an EBS volume
  • Stored in Amazon S3 (managed by AWS)
  • Incremental (only changes are saved)

Think like:

Snapshot = Photo of your disk πŸ“Έ Volume = Live hard disk πŸ’Ύ


🧠 VERY IMPORTANT RULES (MEMORIZE)

βœ” Snapshots are AZ-independent βœ” Volumes are AZ-dependent βœ” Snapshots are incremental βœ” Used for backup & restore


πŸ”Ή STEP 1: Put Test Data on EBS Volume

SSH into your EC2:

ssh -i ec2-key-hands-on.pem ec2-user@ELASTIC_IP

Create a test file:

sudo echo "EBS Snapshot Test File" > /data/test.txt

Verify:

cat /data/test.txt

πŸ”Ή STEP 2: Create Snapshot

  1. AWS Console β†’ EC2
  2. Left menu β†’ Volumes
  3. Select volume ebs-hands-on-1
  4. Actions β†’ Create snapshot

Details:

  • Name:
snapshot-ebs-hands-on-1
  • Description:
Backup before changes

Click Create snapshot


πŸ”Ή STEP 3: Verify Snapshot

  1. Go to Snapshots
  2. Status β†’ Completed

πŸ“Œ Snapshot is safely stored


πŸ”Ή STEP 4: Create NEW Volume from Snapshot

  1. Select snapshot
  2. Actions β†’ Create volume

Settings:

  • Volume type β†’ gp3
  • Availability Zone β†’ Same as EC2
  • Size β†’ Leave default
  • Name:
ebs-restored-from-snapshot

Click Create volume


πŸ”Ή STEP 5: Attach Restored Volume to EC2

  1. Select new volume
  2. Actions β†’ Attach volume
  3. Instance β†’ ec2-hands-on-1
  4. Device β†’ /dev/xvdg
  5. Attach

πŸ”Ή STEP 6: Verify New Disk Inside EC2

lsblk

You should see:

  • xvdg β†’ restored volume

πŸ”Ή STEP 7: Mount Restored Volume

Create mount folder:

sudo mkdir /restore

Mount:

sudo mount /dev/xvdg /restore

πŸ”Ή STEP 8: VERIFY DATA RECOVERY (MOST IMPORTANT)

ls /restore
cat /restore/test.txt

πŸŽ‰ Output:

EBS Snapshot Test File

βœ… Backup & restore successful


🧠 REAL-WORLD USE CASES

  • Backup before OS upgrade
  • Disaster recovery
  • Clone environments
  • Create AMIs
  • Cross-region backup (copy snapshot)

🧠 INTERVIEW-READY ANSWER

An EBS snapshot is an incremental backup of an EBS volume stored in Amazon S3. Snapshots are AZ-independent and can be used to restore volumes or create new volumes across Availability Zones.


⚠️ COMMON MISTAKES

  • ❌ Creating volume in wrong AZ
  • ❌ Forgetting to mount restored volume
  • ❌ Assuming snapshot is full copy (it’s incremental)
  • ❌ Deleting snapshot before restore

βœ… LAB 12 TASK CHECKLIST

  • βœ” Created snapshot
  • βœ” Restored volume
  • βœ” Attached to EC2
  • βœ” Mounted volume
  • βœ” Verified recovered data

πŸ§ͺ EC2 HANDS-ON – LAB 13

πŸ‘‰ Create Custom AMI (Golden Image for EC2)

Image


🎯 Objective of LAB 13

By the end of this lab, you will:

  • Create a custom AMI
  • Launch new EC2 from that AMI
  • Prove pre-installed software exists
  • Understand Golden AMI concept
  • Be interview-ready

🧠 FIRST: What is an AMI? (Simple Words)

An AMI (Amazon Machine Image) is:

  • A template for EC2

  • Contains:

    • OS
    • Installed software
    • Configurations
  • Used to launch multiple identical EC2s

Think like:

AMI = Clone of your configured server 🧬


🧠 GOLDEN AMI (VERY IMPORTANT)

A Golden AMI:

  • Has OS patches
  • Has required software
  • Has security hardening
  • Used across environments

πŸ“Œ Used by:

  • Auto Scaling
  • Dev / QA / Prod

πŸ”Ή STEP 1: Prepare Your EC2 for AMI

We’ll use:

ec2-hands-on-1

Confirm:

  • Apache installed
  • Website working
  • EBS attached

(Optional check):

systemctl status httpd

πŸ”Ή STEP 2: Create AMI from EC2

  1. EC2 Console β†’ Instances
  2. Select ec2-hands-on-1
  3. Actions β†’ Image and templates
  4. Click Create image

Fill Details:

  • Image name:
ec2-golden-ami-v1
  • Description:
Apache + custom configuration
  • Leave defaults (Reboot = YES)

Click Create image

πŸ“Œ AWS creates:

  • AMI
  • Snapshots of attached EBS volumes

πŸ”Ή STEP 3: Track AMI Creation

  1. Go to AMIs
  2. Status β†’ Pending β†’ Available

πŸ“Œ Wait until Available


πŸ”Ή STEP 4: Launch New EC2 from Custom AMI

  1. Select AMI ec2-golden-ami-v1
  2. Click Launch instance from AMI

Configure:

  • Instance name:
ec2-from-golden-ami
  • Instance type β†’ t2.micro
  • Key pair β†’ existing
  • Security group β†’ allow HTTP + SSH
  • Launch

πŸ”Ή STEP 5: Test NEW EC2

  1. Copy Public IP
  2. Open browser:
http://PUBLIC_IP

πŸŽ‰ Website should load immediately ❌ No installation needed


πŸ”Ή STEP 6: PROOF (Optional SSH)

SSH into new EC2:

ssh -i ec2-key-hands-on.pem ec2-user@NEW_PUBLIC_IP

Check:

systemctl status httpd

Result:

active (running)

🧠 REAL-WORLD USE CASES

  • βœ” Auto Scaling Groups
  • βœ” Faster deployments
  • βœ” Consistent environments
  • βœ” Rollback strategy

🧠 INTERVIEW-READY ANSWER

An AMI is a pre-configured template containing the operating system, applications, and settings required to launch EC2 instances. A Golden AMI ensures consistency and faster provisioning across environments.


⚠️ IMPORTANT BEST PRACTICES

  • βœ” Version your AMIs
  • βœ” Patch before AMI creation
  • βœ” Delete unused AMIs
  • βœ” Tag AMIs properly

βœ… LAB 13 TASK CHECKLIST

  • βœ” Created custom AMI
  • βœ” Launched EC2 from AMI
  • βœ” Website worked instantly
  • βœ” Understood Golden AMI concept

πŸ§ͺ EC2 HANDS-ON – LAB 14

πŸ‘‰ Root Volume vs Additional EBS Volumes (Deep Practical Understanding)

Image


🎯 Objective of LAB 14

By the end of this lab, you will:

  • Clearly understand root volume
  • Understand additional EBS volumes
  • See Delete on Termination in action
  • Know real-world best practices
  • Be interview-ready

🧠 FIRST: What is Root Volume? (Simple Words)

The root volume:

  • Contains the OS (Amazon Linux)
  • Is attached at launch
  • Usually named:
/dev/xvda

Think like:

Root volume = Laptop C: drive πŸ’»

Without root volume β†’ EC2 cannot boot


🧠 What is Additional EBS Volume?

Additional EBS:

  • Extra disks you attach later

  • Used for:

    • App data
    • Logs
    • Databases
  • Examples:

/dev/xvdf
/dev/xvdg

Think like:

Additional EBS = External hard disk πŸ’Ύ


πŸ”Ή STEP 1: Identify Volumes on Your EC2

SSH into EC2:

ssh -i ec2-key-hands-on.pem ec2-user@ELASTIC_IP

Run:

lsblk

You will see:

  • xvda β†’ Root volume
  • xvdf β†’ Additional EBS
  • xvdg β†’ Snapshot-restored EBS

πŸ”Ή STEP 2: Check Mount Points

df -h

You will see:

  • / β†’ Root volume
  • /data β†’ Additional EBS
  • /restore β†’ Snapshot EBS

πŸ“Œ Root volume mounts at /


πŸ”Ή STEP 3: Check β€œDelete on Termination” (IMPORTANT)

  1. EC2 Console β†’ Instances
  2. Select ec2-hands-on-1
  3. Go to Storage tab
  4. Click Volume ID of root volume

Look for:

Delete on termination: Yes

πŸ“Œ Meaning:

  • If EC2 terminates
  • Root volume is deleted

πŸ”Ή STEP 4: Check Additional EBS Delete Behavior

Click additional EBS volume:

You’ll see:

Delete on termination: No

πŸ“Œ Meaning:

  • Data survives EC2 termination
  • Used for backups & safety

πŸ”Ή STEP 5: PRACTICAL SCENARIO (CONCEPT)

If EC2 is TERMINATED:

Volume TypeResult
Root volume❌ Deleted
Additional EBSβœ… Preserved

πŸ“Œ That’s why:

  • App data should be on separate EBS
  • OS only on root

πŸ”Ή STEP 6: BEST PRACTICE (REAL WORLD)

  • βœ” Keep OS on root volume
  • βœ” Keep data/logs on separate EBS
  • βœ” Disable delete-on-termination for critical volumes
  • βœ” Take snapshots regularly

🧠 INTERVIEW-READY ANSWER

The root volume contains the operating system and is required for booting an EC2 instance, while additional EBS volumes are used for application data. By default, the root volume is deleted on termination, whereas additional volumes persist unless explicitly configured otherwise.


⚠️ COMMON MISTAKES

  • ❌ Storing critical data on root volume
  • ❌ Not checking delete-on-termination
  • ❌ Forgetting to back up additional volumes

βœ… LAB 14 TASK CHECKLIST

  • βœ” Identified root vs additional volumes
  • βœ” Checked mount points
  • βœ” Understood delete-on-termination
  • βœ” Learned real-world design practice

πŸ§ͺ EC2 HANDS-ON – LAB 15

πŸ‘‰ EBS vs Instance Store (Performance vs Persistence)


🎯 Objective of LAB 15

By the end of this lab, you will:

  • Understand Instance Store
  • Compare EBS vs Instance Store
  • Know when to use each
  • Be interview-ready

🧠 FIRST: What is Instance Store?

Instance Store is:

  • Temporary (ephemeral) storage

  • Physically attached to EC2 host

  • Data is lost if:

    • Instance stops
    • Instance terminates
    • Host fails

Think like:

Instance Store = RAM disk / temporary scratch space ⚑


🧠 What is EBS? (Reminder)

EBS:

  • Persistent block storage
  • Independent of EC2 lifecycle
  • Backed by AWS-managed infrastructure

Think like:

EBS = External hard disk πŸ’Ύ


πŸ”Ή HANDS-ON NOTE (IMPORTANT)

⚠️ Free Tier usually does NOT support Instance Store

So we’ll do:

  • Conceptual + console visibility
  • Real-world explanation (interview focus)

πŸ”Ή STEP 1: Identify Instance Store Support

  1. EC2 β†’ Launch instance

  2. Select an instance type like:

    • i3, i4, d2

You’ll see:

Instance store volumes available

πŸ“Œ These instance types support instance store


πŸ”Ή STEP 2: Understand Storage at Launch

When instance store is used:

  • Disk appears as:
/dev/nvme1n1
  • Must be formatted manually
  • Not persistent

πŸ”Ή STEP 3: EBS vs Instance Store (INTERVIEW TABLE)

FeatureEBSInstance Store
Persistenceβœ… Yes❌ No
Data survives stopβœ… Yes❌ No
Snapshotβœ… Yes❌ No
PerformanceGoodVery High
CostPaidIncluded
Use caseDatabasesCache / temp

πŸ”Ή STEP 4: REAL-WORLD USE CASES

Use EBS when:

  • βœ” Databases
  • βœ” App data
  • βœ” Logs
  • βœ” Backups

Use Instance Store when:

  • βœ” Cache
  • βœ” Buffer
  • βœ” Temporary data
  • βœ” High-speed scratch space

🧠 INTERVIEW-READY ANSWER

Amazon EBS provides persistent block storage independent of the EC2 lifecycle, whereas Instance Store offers high-performance, ephemeral storage that is lost when the instance stops or terminates.


⚠️ COMMON MISTAKES

  • ❌ Using instance store for databases
  • ❌ Expecting data persistence
  • ❌ No backups

βœ… LAB 15 TASK CHECKLIST

  • βœ” Understood instance store
  • βœ” Compared with EBS
  • βœ” Learned performance trade-offs
  • βœ” Interview clarity achieved

πŸ§ͺ EC2 HANDS-ON – LAB 16

πŸ‘‰ Multi-AZ EC2 Deployment (High Availability Basics)

Image


🎯 Objective of LAB 16

By the end of this lab, you will:

  • Understand Availability Zones (AZs) deeply
  • Launch EC2 instances in multiple AZs
  • Prove why Multi-AZ is needed
  • Be able to explain HA architecture in interviews

🧠 FIRST: What is an Availability Zone? (Very Simple)

An Availability Zone (AZ) is:

  • One or more physically separate data centers
  • Inside a single AWS region
  • Connected with high-speed private network

Example (Mumbai region):

ap-south-1a
ap-south-1b
ap-south-1c

Think like:

Region = City πŸ™οΈ AZ = Different buildings in the city 🏒🏒🏒


🧠 Why Multi-AZ is IMPORTANT?

If you use only ONE AZ:

  • Power failure ❌
  • Network issue ❌
  • Fire / flood ❌ ➑️ Your application goes DOWN

If you use MULTI-AZ:

  • One AZ fails ❌
  • Other AZ still works βœ… ➑️ Application stays UP

πŸ‘‰ This is called High Availability


πŸ”Ή STEP 1: Check AZ of Your Existing EC2

  1. EC2 β†’ Instances
  2. Select ec2-hands-on-1
  3. Check:
Availability Zone

Example:

ap-south-1a

πŸ“Œ Right now β†’ Single-AZ architecture


πŸ”Ή STEP 2: Launch SECOND EC2 in DIFFERENT AZ

We will launch another EC2, but in a different AZ.

Launch Instance:

  • Name:
ec2-hands-on-az2
  • AMI: Amazon Linux 2023

  • Instance type: t2.micro

  • Key pair: existing

  • Security group:

    • SSH (22) β†’ My IP
    • HTTP (80) β†’ Anywhere

πŸ”₯ IMPORTANT (AZ SELECTION)

In Network settings β†’ Subnet:

  • Select a subnet from a different AZ

Example:

  • First EC2 β†’ ap-south-1a
  • Second EC2 β†’ ap-south-1b

πŸ“Œ This step is CRITICAL


πŸ”Ή STEP 3: Launch & Verify

Wait until: 🟒 Instance state β†’ Running

Now you have:

  • EC2 in AZ-A
  • EC2 in AZ-B

βœ… Multi-AZ setup achieved


πŸ”Ή STEP 4: Install Apache on SECOND EC2

SSH into second EC2:

ssh -i ec2-key-hands-on.pem ec2-user@SECOND_PUBLIC_IP

Install Apache:

sudo dnf install httpd -y
sudo systemctl start httpd
sudo systemctl enable httpd

Create page:

echo "<h1>Hello from AZ-2 EC2</h1>" | sudo tee /var/www/html/index.html

πŸ”Ή STEP 5: Test Both EC2s

Browser tests:

EC2-1 (AZ-A):

http://IP-OF-EC2-1

EC2-2 (AZ-B):

http://IP-OF-EC2-2

βœ… Both websites work independently


πŸ”Ή STEP 6: FAILURE SCENARIO (CONCEPTUAL)

Imagine:

  • AZ-A goes DOWN ❌

What happens?

SetupResult
Single-AZApp DOWN ❌
Multi-AZApp STILL UP βœ…

πŸ“Œ This is why AWS recommends Multi-AZ


🧠 VERY IMPORTANT INTERVIEW POINTS

βœ” Multi-AZ β‰  Auto Scaling βœ” Multi-AZ β‰  Load Balancer βœ” Multi-AZ = Design choice βœ” HA requires more than one AZ


🧠 INTERVIEW-READY ANSWER

A Multi-AZ architecture deploys EC2 instances across multiple Availability Zones within a region to ensure high availability and fault tolerance. If one AZ fails, traffic can be served from another AZ.


⚠️ COMMON MISTAKES

❌ Launching both EC2s in same AZ ❌ Assuming region = AZ ❌ Thinking Multi-AZ happens automatically


βœ… LAB 16 TASK CHECKLIST

βœ” Identified AZ of EC2 βœ” Launched second EC2 in different AZ βœ” Installed Apache on second EC2 βœ” Tested both independently βœ” Understood HA concept


πŸ§ͺ EC2 HANDS-ON – LAB 17

πŸ‘‰ Application Load Balancer (ALB) – Distribute Traffic Across AZs

Image


🎯 Objective of LAB 17

By the end of this lab, you will:

  • Create an Application Load Balancer
  • Route traffic to multiple EC2s
  • Understand Target Groups & Health Checks
  • Achieve true High Availability
  • Be 100% interview-ready

🧠 FIRST: What is a Load Balancer? (Simple Words)

A Load Balancer:

  • Receives traffic from users
  • Distributes it across multiple EC2 instances
  • Prevents overload & downtime

Think like:

Load Balancer = Traffic police 🚦


🧠 What is ALB?

Application Load Balancer (ALB):

  • Works at Layer 7 (HTTP/HTTPS)

  • Routes based on:

    • URL path
    • Host name
  • Supports Auto Scaling

ALB is part of Amazon Web Services β†’ Elastic Load Balancing


🧠 ARCHITECTURE YOU ARE BUILDING

User
 ↓
Application Load Balancer
 ↓            ↓
EC2 (AZ-A)   EC2 (AZ-B)

πŸ”Ή STEP 1: Create Target Group

Target Group = Group of EC2s ALB sends traffic to

  1. AWS Console β†’ EC2
  2. Left menu β†’ Target Groups
  3. Click Create target group

Configure:

  • Target type β†’ Instances
  • Name:
tg-ec2-hands-on
  • Protocol β†’ HTTP
  • Port β†’ 80
  • VPC β†’ your VPC
  • Health check path:
/

Click Next


πŸ”Ή STEP 2: Register EC2 Instances

  1. Select BOTH EC2 instances:

    • ec2-hands-on-1
    • ec2-hands-on-az2
  2. Click Include as pending

  3. Click Create target group


πŸ”Ή STEP 3: Create Application Load Balancer

  1. EC2 β†’ Load Balancers
  2. Click Create Load Balancer
  3. Select Application Load Balancer

Basic Configuration

  • Name:
alb-ec2-hands-on
  • Scheme β†’ Internet-facing
  • IP address type β†’ IPv4
FeatureInternet-facingInternal
Accessible from internetβœ… Yes❌ No
IP typePublic IPsPrivate IPs
Subnet typePublic subnetPrivate subnet
Common useWebsites, APIsBackend services
DNS resolves toPublic IPsPrivate IPs

Network Mapping (IMPORTANT)

  • VPC β†’ your VPC

  • Select at least 2 AZs

    • ap-south-1a
    • ap-south-1b

πŸ“Œ ALB must be Multi-AZ


Security Group

  • Create new SG:

    • HTTP (80) β†’ Anywhere
  • Name:

alb-sg

Listener & Routing

  • Listener β†’ HTTP : 80
  • Default action β†’ Forward to:
tg-ec2-hands-on

Click Create load balancer


πŸ”Ή STEP 4: Wait for ALB to Become Active

Status:

Provisioning β†’ Active

Copy:

DNS name

Example:

alb-ec2-hands-on-123.ap-south-1.elb.amazonaws.com

πŸ”Ή STEP 5: Test Load Balancer (FUN PART πŸŽ‰)

Open browser:

http://ALB_DNS_NAME

Refresh multiple times πŸ”„

You should see:

  • Sometimes: Hello from AZ-1
  • Sometimes: Hello from AZ-2

βœ… Traffic is distributed


πŸ”Ή STEP 6: Health Check Verification

  1. EC2 β†’ Target Groups
  2. Select tg-ec2-hands-on
  3. Check Targets

Both instances should be:

Healthy

πŸ”Ή STEP 7: FAILURE TEST (VERY IMPORTANT)

Stop ONE EC2 instance:

  • Stop ec2-hands-on-az2

Now refresh ALB URL again πŸ‘‡

🟒 Website STILL works πŸ“Œ Traffic goes only to healthy EC2

πŸ‘‰ THIS IS HIGH AVAILABILITY


🧠 INTERVIEW-READY ANSWER

An Application Load Balancer operates at Layer 7 and distributes HTTP/HTTPS traffic across multiple targets in different Availability Zones. It uses health checks to route traffic only to healthy instances, ensuring high availability.


🧠 VERY IMPORTANT INTERVIEW POINTS

βœ” ALB is regional βœ” ALB is Multi-AZ by default βœ” ALB uses Target Groups βœ” ALB performs health checks βœ” ALB does NOT host applications


⚠️ COMMON MISTAKES

❌ Not opening HTTP in EC2 SG ❌ Not opening HTTP in ALB SG ❌ Registering wrong instances ❌ Using only one AZ


βœ… LAB 17 TASK CHECKLIST

βœ” Created Target Group βœ” Registered EC2s βœ” Created ALB βœ” Verified traffic distribution βœ” Tested failure scenario


πŸ§ͺ EC2 HANDS-ON – LAB 18

πŸ‘‰ Target Groups & Health Checks (Deep Dive + Failure Control)

Image


🎯 Objective of LAB 18

By the end of this lab, you will:

  • Fully understand Target Groups
  • Customize Health Checks
  • See how instances become Healthy / Unhealthy
  • Control traffic without stopping EC2
  • Be interview + production ready

🧠 FIRST: What is a Target Group? (Simple Words)

A Target Group:

  • Is a logical group of backend resources

  • ALB sends traffic only to healthy targets

  • Can contain:

    • EC2 instances
    • IP addresses
    • Lambda (not now)

Think like:

Target Group = Team of workers πŸ‘· ALB = Manager who sends work only to active workers


🧠 VERY IMPORTANT CONCEPT

ALB never sends traffic directly to EC2 It sends traffic via Target Groups

πŸ“Œ This gives:

  • Flexibility
  • Health control
  • Scaling support

πŸ”Ή STEP 1: Open Target Group Settings

  1. EC2 Console β†’ Target Groups
  2. Select:
tg-ec2-hands-on
  1. Go to Health checks tab
  2. Click Edit

πŸ”Ή STEP 2: Understand Health Check Settings

Default values (important):

SettingMeaning
ProtocolHTTP
Path/
Porttraffic port (80)
Healthy threshold5
Unhealthy threshold2
Timeout5 sec
Interval30 sec

πŸ“Œ ALB checks:

http://EC2-IP:80/

If it fails β†’ instance marked Unhealthy


πŸ”Ή STEP 3: CREATE A CUSTOM HEALTH CHECK PAGE (Hands-On)

SSH into EC2 in AZ-A:

ssh -i ec2-key-hands-on.pem ec2-user@EC2_A_IP

Create health page:

echo "OK" | sudo tee /var/www/html/health

Repeat same on EC2 in AZ-B.


πŸ”Ή STEP 4: Update Target Group Health Check Path

Back to Target Group β†’ Health checks β†’ Edit

Change:

Path: /health

Save changes

⏳ Wait ~1 minute


πŸ”Ή STEP 5: Verify Health Status

Go to: Target Groups β†’ Targets

You should see:

Healthy

πŸ“Œ Health is now checked via /health


πŸ”Ή STEP 6: BREAK ONE INSTANCE (NO STOP)

SSH into EC2-A:

sudo rm /var/www/html/health

πŸ”Ή STEP 7: Observe ALB Behavior (CRITICAL)

Wait ~1 minute

Now check: Target Groups β†’ Targets

EC2-A status:

Unhealthy

EC2-B:

Healthy

πŸ”Ή STEP 8: Test in Browser

Open:

http://ALB_DNS_NAME

🟒 Website STILL works πŸ“Œ Traffic goes only to healthy EC2

πŸ‘‰ This is zero-downtime protection


πŸ”Ή STEP 9: FIX THE INSTANCE

On EC2-A:

echo "OK" | sudo tee /var/www/html/health

Wait ~1 minute

Status becomes:

Healthy

Traffic resumes automatically


🧠 VERY IMPORTANT INTERVIEW POINTS

βœ” Health checks prevent bad traffic βœ” EC2 can be running but unhealthy βœ” ALB removes unhealthy targets automatically βœ” No manual intervention needed


🧠 INTERVIEW-READY ANSWER

Target Groups define the backend resources for a load balancer, and health checks continuously monitor the availability of each target. The load balancer routes traffic only to healthy targets, ensuring fault tolerance and zero downtime.


⚠️ COMMON MISTAKES

❌ Wrong health check path ❌ App returns 404 / 500 ❌ Health check port blocked in SG ❌ Assuming β€œrunning” means β€œhealthy”


βœ… LAB 18 TASK CHECKLIST

βœ” Understood Target Groups βœ” Created custom health endpoint βœ” Modified health check path βœ” Forced unhealthy state βœ” Observed ALB traffic control


πŸ§ͺ EC2 HANDS-ON – LAB 19

πŸ‘‰ Auto Scaling Group (ASG) – Automatically Scale EC2

Image


🎯 Objective of LAB 19

By the end of this lab, you will:

  • Understand what Auto Scaling is
  • Create an Auto Scaling Group
  • Automatically add/remove EC2 instances
  • Attach ASG to Application Load Balancer
  • Be 100% interview + real-world ready

🧠 FIRST: What is Auto Scaling? (Very Simple)

Auto Scaling:

  • Automatically launches EC2 instances

  • Automatically terminates EC2 instances

  • Based on:

    • Load (CPU)
    • Health
    • Capacity rules

Think like:

Auto Scaling = Smart system that hires & fires workers automatically πŸ€–


🧠 WHY Auto Scaling is IMPORTANT?

Without Auto Scaling:

  • High traffic β†’ app crashes ❌
  • Low traffic β†’ money wasted ❌

With Auto Scaling:

  • High traffic β†’ more EC2s βœ…
  • Low traffic β†’ fewer EC2s βœ…

πŸ‘‰ Performance + Cost optimization


🧠 ARCHITECTURE WE ARE BUILDING

Users
 ↓
Application Load Balancer
 ↓
Auto Scaling Group
 ↓        ↓        ↓
EC2 (AZ-A) EC2 (AZ-B) EC2 (AZ-C)

πŸ”Ή STEP 1: Create Launch Template (MOST IMPORTANT)

Auto Scaling uses a Launch Template to create EC2s.

Go to:

EC2 β†’ Launch Templates β†’ Create launch template


Configure Launch Template

Launch template name

lt-ec2-hands-on

AMI

  • Select your custom AMI:
ec2-golden-ami-v1

πŸ“Œ This ensures:

  • Apache already installed
  • Website ready instantly

Instance type

t2.micro

Key pair

ec2-key-hands-on

Network settings

  • Do NOT select subnet here

  • Security group:

    • SSH (22) β†’ My IP
    • HTTP (80) β†’ ALB SG (recommended)

πŸ“Œ EC2 should accept traffic only from ALB


Advanced details

  • Leave empty (no user data now)

Click Create launch template


πŸ”Ή STEP 2: Create Auto Scaling Group

  1. Go to Auto Scaling Groups
  2. Click Create Auto Scaling group

Basic Settings

  • Name:
asg-ec2-hands-on
  • Launch template:
lt-ec2-hands-on

Click Next


Network Settings (VERY IMPORTANT)

  • VPC β†’ your VPC

  • Subnets β†’ select at least 2 AZs

    • ap-south-1a
    • ap-south-1b

πŸ“Œ This makes ASG Multi-AZ


Attach Load Balancer

  • Select:
Attach to an existing load balancer
  • Choose:
Application Load Balancer
  • Select target group:
tg-ec2-hands-on

Click Next


πŸ”Ή STEP 3: Configure Group Size

Set:

  • Desired capacity β†’ 2
  • Minimum capacity β†’ 1
  • Maximum capacity β†’ 3

πŸ“Œ Meaning:

  • At least 1 EC2 always running
  • Normally 2 EC2s
  • Max 3 during traffic spike

πŸ”Ή STEP 4: Configure Scaling Policy

Choose:

Target tracking scaling policy

Metric:

Average CPU utilization

Target value:

50%

πŸ“Œ If CPU > 50% β†’ scale OUT πŸ“Œ If CPU < 50% β†’ scale IN

Click Next β†’ Create Auto Scaling group


πŸ”Ή STEP 5: VERIFY ASG CREATION

Go to: Auto Scaling Groups β†’ asg-ec2-hands-on

You should see:

  • 2 EC2 instances launching automatically

πŸ“Œ You did NOT manually create them!


πŸ”Ή STEP 6: VERIFY ALB INTEGRATION

  1. Go to Target Groups

  2. Open tg-ec2-hands-on

  3. Targets β†’ You’ll see:

    • ASG-created EC2s
    • Status = Healthy

πŸ”Ή STEP 7: TEST AUTO SCALING (CONCEPTUAL + OPTIONAL)

To simulate load:

sudo yum install stress -y
stress --cpu 2

πŸ“Œ CPU goes high β†’ ASG launches new EC2

(We can skip actual stress to save free tier)

you can also stop one EC2 to see ASG replace it. for that just terminate one of the ASG EC2s from console.


🧠 VERY IMPORTANT INTERVIEW POINTS

βœ” ASG uses Launch Template βœ” ASG is Multi-AZ βœ” ASG replaces unhealthy EC2s βœ” ASG works with ALB βœ” ASG = High Availability + Scalability


🧠 INTERVIEW-READY ANSWER

An Auto Scaling Group automatically adjusts the number of EC2 instances based on demand and health checks. It ensures high availability, fault tolerance, and cost efficiency by scaling out during high load and scaling in during low usage.


⚠️ COMMON MISTAKES

❌ Using default AMI instead of Golden AMI ❌ Single AZ ASG ❌ Wrong security group (ALB traffic blocked) ❌ No scaling policy


βœ… LAB 19 TASK CHECKLIST

βœ” Created Launch Template βœ” Created Auto Scaling Group βœ” Multi-AZ configuration βœ” Integrated with ALB βœ” Understood scaling logic


πŸ§ͺ EC2 HANDS-ON – LAB 20

πŸ‘‰ High Availability EC2 Architecture (End-to-End Design)

Image


🎯 Objective of LAB 20

By the end of this lab, you will:

  • Understand complete HA EC2 architecture
  • Know how each component works together
  • Be able to design & explain production systems
  • Be interview + real-world ready

🧠 COMPLETE ARCHITECTURE (WHAT YOU BUILT)

Users
 ↓
Route 53 (DNS)
 ↓
Application Load Balancer (Multi-AZ)
 ↓
Auto Scaling Group
 ↓        ↓        ↓
EC2 (AZ-A) EC2 (AZ-B) EC2 (AZ-C)
 ↓
EBS (Persistent Storage)

🧠 COMPONENT-BY-COMPONENT BREAKDOWN


πŸ”Ή DNS – Amazon Route 53

  • Maps domain β†’ ALB
  • Health checks (optional)
  • Highly available globally

πŸ”Ή Application Load Balancer

  • Internet-facing
  • Distributes traffic
  • Health checks targets
  • Multi-AZ by default

πŸ”Ή Auto Scaling Group

  • Maintains desired EC2 count
  • Scales in/out automatically
  • Replaces unhealthy EC2s
  • Uses Launch Template + Golden AMI

πŸ”Ή EC2 Instances

  • Stateless compute layer
  • No data stored locally
  • Created automatically

πŸ”Ή EBS

  • Persistent storage
  • Independent of EC2 lifecycle
  • Used for logs / app data

πŸ”Ή FAILURE SCENARIOS (CRITICAL THINKING)

Scenario 1: EC2 Failure ❌

  • ASG launches new EC2 automatically
  • ALB routes traffic to healthy targets

Scenario 2: AZ Failure ❌

  • ALB routes traffic to other AZs
  • ASG launches instances in healthy AZs

Scenario 3: Traffic Spike πŸš€

  • CPU increases
  • ASG scales out automatically
  • Performance maintained

Scenario 4: Traffic Drop πŸ“‰

  • ASG scales in
  • Cost optimized

🧠 WHY THIS ARCHITECTURE IS PRODUCTION-READY

βœ” No single point of failure βœ” Horizontally scalable βœ” Cost efficient βœ” Secure & resilient βœ” Fully automated


🧠 INTERVIEW DESIGN ANSWER (GOLD)

I would design a highly available EC2 architecture using Route 53 for DNS, an internet-facing Application Load Balancer, Auto Scaling Groups across multiple Availability Zones, and EC2 instances launched from a Golden AMI. This ensures fault tolerance, scalability, and zero downtime.


🧠 COMMON INTERVIEW FOLLOW-UP QUESTIONS

QuestionAnswer
Single EC2 down?ASG replaces
AZ down?ALB routes elsewhere
Scale during traffic?ASG
Static IP needed?ALB DNS / Route 53
Data persistence?EBS / RDS

🏁 PHASE COMPLETED πŸŽ‰

You have completed: βœ… Core EC2 βœ… Storage βœ… Networking βœ… Load Balancing βœ… Auto Scaling βœ… High Availability


πŸ§ͺ EC2 HANDS-ON – LAB 21

πŸ‘‰ Amazon CloudWatch (Monitoring, Metrics & Alarms)

Image

Image


🎯 Objective of LAB 21

By the end of this lab, you will:

  • Understand what CloudWatch is
  • Monitor EC2 metrics (CPU, Network, Disk)
  • Create a CloudWatch Alarm
  • Trigger an alarm practically
  • Be interview + production ready

🧠 FIRST: What is CloudWatch? (Very Simple)

CloudWatch is:

  • AWS monitoring service
  • Collects metrics, logs, events
  • Helps you see & react to problems

Think like:

CloudWatch = CCTV + Health monitor for AWS resources πŸ“Š


🧠 What CloudWatch Does for EC2

CloudWatch can: βœ” Monitor CPU usage βœ” Monitor network traffic βœ” Trigger alarms βœ” Help Auto Scaling βœ” Reduce downtime


πŸ”Ή STEP 1: Open CloudWatch

  1. AWS Console
  2. Search CloudWatch
  3. Open CloudWatch Dashboard

πŸ”Ή STEP 2: View EC2 Metrics

  1. Left menu β†’ Metrics
  2. Click EC2
  3. Click Per-Instance Metrics
  4. Select one EC2 from ASG or ec2-hands-on-1

You’ll see metrics like:

  • CPUUtilization
  • NetworkIn
  • NetworkOut
  • DiskReadOps

πŸ“Œ These are real-time performance data


πŸ”Ή STEP 3: View CPU Utilization Graph

  1. Select CPUUtilization
  2. Click Graphed metrics

You’ll see:

  • Time on X-axis
  • CPU % on Y-axis

πŸ“Œ This is what ASG uses for scaling


πŸ”Ή STEP 4: Create a CloudWatch Alarm (IMPORTANT)

Now we create an alarm on CPU usage.

  1. Select CPUUtilization
  2. Click Create alarm

Alarm Configuration

Metric

  • CPUUtilization

Condition

  • Threshold type β†’ Static
  • Whenever CPUUtilization Greater than
70%

Notification

  • Alarm state trigger β†’ In alarm

πŸ“Œ For now:

  • Choose Create new SNS topic
  • Email β†’ your email
  • Confirm subscription from email (IMPORTANT)

Alarm Name

ec2-high-cpu-alarm

Click Create alarm


πŸ”Ή STEP 5: Verify Alarm Status

Go to: CloudWatch β†’ Alarms

Status initially:

OK

πŸ“Œ Alarm watches EC2 continuously


πŸ”Ή STEP 6: Trigger Alarm (Hands-On)

SSH into EC2:

ssh -i ec2-key-hands-on.pem ec2-user@EC2_PUBLIC_IP

Install stress tool:

sudo yum install stress -y

Run stress:

stress --cpu 2

πŸ“Œ This increases CPU usage


πŸ”Ή STEP 7: Observe Alarm State Change

Wait ~1–2 minutes

Alarm status changes:

OK β†’ ALARM

πŸ“§ You receive email alert

πŸŽ‰ Monitoring + alerting works


πŸ”Ή STEP 8: Stop Stress Test

Press:

CTRL + C

After few minutes:

ALARM β†’ OK

🧠 VERY IMPORTANT INTERVIEW POINTS

βœ” CloudWatch metrics are automatic βœ” Alarms trigger actions or notifications βœ” ASG uses CloudWatch metrics βœ” Default EC2 metrics are every 5 minutes βœ” Detailed monitoring = 1 minute


🧠 INTERVIEW-READY ANSWER

Amazon CloudWatch is a monitoring service that collects metrics, logs, and events from AWS resources. It enables real-time visibility, alarm-based notifications, and automated actions such as Auto Scaling.


⚠️ COMMON MISTAKES

❌ Forgetting to confirm SNS email ❌ Expecting disk usage without agent ❌ Setting wrong threshold ❌ Monitoring wrong instance


βœ… LAB 21 TASK CHECKLIST

βœ” Viewed EC2 metrics βœ” Understood CPU graph βœ” Created CloudWatch alarm βœ” Triggered alarm practically βœ” Received notification


πŸ§ͺ EC2 HANDS-ON – LAB 22

πŸ‘‰ CloudWatch Alarms + Auto Scaling (Automatic Scale Out & In)

Image


🎯 Objective of LAB 22

By the end of this lab, you will:

  • Connect CloudWatch β†’ Auto Scaling
  • Create scale-out & scale-in alarms
  • See EC2 instances launch automatically
  • Understand how AWS self-heals
  • Be interview + real-world ready

🧠 FIRST: How This Works (Simple Flow)

High CPU
 ↓
CloudWatch Alarm
 ↓
Auto Scaling Policy
 ↓
New EC2 launched

And reverse for scale-in.

Think like:

CloudWatch = Sensor πŸ“ˆ Auto Scaling = Action πŸ€–


🧠 IMPORTANT CONCEPT

  • CloudWatch detects
  • Auto Scaling reacts
  • You do nothing manually

πŸ”Ή STEP 1: Open Your Auto Scaling Group

  1. EC2 Console β†’ Auto Scaling Groups
  2. Select:
asg-ec2-hands-on
  1. Open Automatic scaling tab

You will see:

  • Existing Target tracking policy (CPU 50%)

πŸ“Œ Target tracking already uses CloudWatch internally Now we’ll explicitly see alarm behavior


πŸ”Ή STEP 2: View Auto-Created CloudWatch Alarms

  1. Open CloudWatch
  2. Go to Alarms
  3. You’ll see alarms like:
TargetTracking-asg-ec2-hands-on-High-CPU
TargetTracking-asg-ec2-hands-on-Low-CPU

πŸ“Œ These were created automatically by ASG


πŸ”Ή STEP 3: Understand These Alarms

High CPU Alarm

  • Trigger: CPU > 50%
  • Action: Scale OUT
  • Adds EC2 instance

Low CPU Alarm

  • Trigger: CPU < 50%
  • Action: Scale IN
  • Removes EC2 instance

πŸ‘‰ This is closed-loop automation


πŸ”Ή STEP 4: Observe Current Capacity

Go back to ASG β†’ Details

Check:

  • Desired: 2
  • Min: 1
  • Max: 3

πŸ“Œ Currently running EC2 = 2


πŸ”Ή STEP 5: Trigger SCALE OUT (Hands-On)

SSH into one ASG EC2 (any):

ssh -i ec2-key-hands-on.pem ec2-user@ASG_EC2_PUBLIC_IP

Install stress:

sudo yum install stress -y

Run:

stress --cpu 2

πŸ”Ή STEP 6: Observe Scaling Activity (IMPORTANT)

  1. ASG β†’ Activity
  2. You’ll see:
Launching a new EC2 instance

Wait 2–5 minutes

Now:

  • EC2 count becomes 3
  • New EC2 automatically registered in Target Group
  • ALB sends traffic to it

πŸŽ‰ AUTO SCALE OUT SUCCESS


πŸ”Ή STEP 7: Verify via Target Group

  1. EC2 β†’ Target Groups
  2. Open tg-ec2-hands-on
  3. Targets β†’ You’ll see 3 healthy instances

πŸ”Ή STEP 8: Trigger SCALE IN

Stop stress:

CTRL + C

Wait few minutes

ASG activity:

Terminating EC2 instance

Now EC2 count β†’ 2

πŸ“Œ Scale-in never goes below minimum capacity


🧠 VERY IMPORTANT INTERVIEW POINTS

βœ” Auto Scaling uses CloudWatch metrics βœ” Alarms can trigger scale out/in βœ” Scaling is automatic & continuous βœ” No human action required βœ” Prevents over-provisioning


🧠 INTERVIEW-READY ANSWER

CloudWatch alarms monitor EC2 metrics such as CPU utilization and trigger Auto Scaling policies to automatically scale out or scale in instances, ensuring performance and cost efficiency.


⚠️ COMMON MISTAKES

❌ Min capacity = 0 (downtime risk) ❌ Wrong metric selection ❌ Expecting instant scaling (it’s gradual) ❌ Forgetting cooldown periods


βœ… LAB 22 TASK CHECKLIST

βœ” Viewed ASG-created alarms βœ” Triggered scale-out βœ” Observed new EC2 launch βœ” Verified via Target Group βœ” Observed scale-in


πŸ§ͺ EC2 HANDS-ON – LAB 23

πŸ‘‰ EC2 Logs & Troubleshooting (CloudWatch Logs + Real Failures)

Image


🎯 Objective of LAB 23

By the end of this lab, you will:

  • Understand where EC2 logs live
  • Send EC2 logs to CloudWatch
  • Debug real website failures
  • Know production troubleshooting flow
  • Be interview + on-call ready

🧠 FIRST: Why Logs Are CRITICAL

Metrics tell you something is wrong Logs tell you WHY it is wrong

Think like:

Metrics = Fever 🌑️ Logs = Doctor report 🩺


🧠 TYPES OF LOGS YOU MUST KNOW

1️⃣ System Logs

  • OS boot issues
  • Kernel problems

2️⃣ Application Logs

  • Apache / Nginx
  • App errors

3️⃣ Cloud Logs

  • Centralized in CloudWatch
  • Used for monitoring & alerting

πŸ”Ή STEP 1: Check EC2 SYSTEM LOG (Console Level)

  1. EC2 β†’ Instances
  2. Select any EC2
  3. Actions β†’ Monitor and troubleshoot
  4. Click Get system log

πŸ“Œ Shows:

  • Boot messages
  • Startup failures

βœ… Used when EC2 won’t start


πŸ”Ή STEP 2: Apache Logs (INSIDE EC2)

SSH into EC2:

ssh -i ec2-key-hands-on.pem ec2-user@EC2_PUBLIC_IP

Apache log locations:

/var/log/httpd/access_log
/var/log/httpd/error_log

View logs:

sudo tail -f /var/log/httpd/access_log

πŸ“Œ Shows:

  • Requests coming to server

πŸ”Ή STEP 3: Simulate an ERROR (Hands-On)

Break Apache config (safe test):

sudo chmod 000 /var/www/html

Now open website in browser ❌ It will fail

Check error log:

sudo tail /var/log/httpd/error_log

You’ll see permission denied errors

πŸ‘‰ This is real troubleshooting


πŸ”Ή STEP 4: FIX the Issue

sudo chmod 755 /var/www/html
sudo systemctl restart httpd

Refresh browser β†’ 🟒 Works again


🧠 LESSON

βœ” Website down β‰  EC2 down βœ” Logs tell exact cause βœ” Restart without checking logs = BAD practice


πŸ”Ή STEP 5: Send EC2 Logs to CloudWatch (IMPORTANT)

Now we centralize logs using CloudWatch Agent.


Install CloudWatch Agent

sudo yum install amazon-cloudwatch-agent -y

πŸ“Œ This agent sends logs β†’ CloudWatch


Create Agent Config File

sudo nano /opt/aws/amazon-cloudwatch-agent/bin/config.json

Paste:

{
  "logs": {
    "logs_collected": {
      "files": {
        "collect_list": [
          {
            "file_path": "/var/log/httpd/error_log",
            "log_group_name": "ec2-apache-error-log",
            "log_stream_name": "{instance_id}"
          }
        ]
      }
    }
  }
}

Save & exit


Start CloudWatch Agent

sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl \
-a fetch-config \
-m ec2 \
-c file:/opt/aws/amazon-cloudwatch-agent/bin/config.json \
-s

πŸ“Œ This command:

  • Reads config
  • Starts agent
  • Pushes logs to CloudWatch

πŸ”Ή STEP 6: View Logs in CloudWatch

  1. Open CloudWatch
  2. Go to Logs β†’ Log groups
  3. Open:
ec2-apache-error-log

πŸŽ‰ You’ll see Apache logs without SSH


🧠 REAL-WORLD BENEFITS

βœ” Debug without server access βœ” Centralized logs βœ” Works with ASG (instances come & go) βœ” Required for compliance & audits


🧠 INTERVIEW-READY ANSWER

EC2 troubleshooting involves analyzing system logs, application logs, and CloudWatch Logs. Centralizing logs in CloudWatch enables faster debugging, monitoring, and troubleshooting across scalable environments.


⚠️ COMMON MISTAKES

❌ Restarting services blindly ❌ Not checking error logs ❌ No centralized logging ❌ SSH-only debugging


βœ… LAB 23 TASK CHECKLIST

βœ” Viewed system logs βœ” Checked Apache logs βœ” Simulated real error βœ” Fixed issue using logs βœ” Sent logs to CloudWatch


πŸ§ͺ EC2 HANDS-ON – LAB 24

πŸ‘‰ IAM Roles for EC2 (Secure AWS Access WITHOUT Access Keys)

Image


🎯 Objective of LAB 24

By the end of this lab, you will:

  • Understand why access keys are dangerous
  • Create an IAM Role
  • Attach the role to an EC2 instance
  • Access AWS services without access keys
  • Be 100% interview + production ready

🧠 FIRST: Why NOT Use Access Keys on EC2?

If you put Access Key + Secret Key inside EC2: ❌ Keys can be stolen ❌ Keys can be leaked in GitHub ❌ Manual rotation required ❌ Security risk

πŸ‘‰ AWS Best Practice: βœ” Use IAM Roles


🧠 What is an IAM Role?

An IAM Role:

  • Is an identity for AWS services
  • Provides temporary credentials
  • Automatically rotated by AWS
  • Attached directly to EC2

Think like:

IAM Role = Temporary ID card 🎫 EC2 uses it automatically


πŸ”Ή IAM SERVICE (Important to Know)

IAM belongs to Amazon Web Services

IAM = Identity and Access Management


🧠 WHAT WE WILL DO IN THIS LAB

We will: 1️⃣ Create IAM Role 2️⃣ Attach S3 read access 3️⃣ Attach role to EC2 4️⃣ Access S3 without keys


πŸ”Ή STEP 1: Create IAM Role

  1. AWS Console β†’ Search IAM
  2. Click Roles
  3. Click Create role

Trusted Entity

  • Select AWS service
  • Use case β†’ EC2
  • Click Next

πŸ“Œ This means: EC2 is allowed to assume this role


πŸ”Ή STEP 2: Attach Permission Policy

Search & select:

AmazonS3ReadOnlyAccess

Click Next

πŸ“Œ This policy allows:

  • List buckets
  • Read objects
  • NO delete access

πŸ”Ή STEP 3: Name the Role

Role name:

ec2-s3-read-role

Click Create role

πŸŽ‰ IAM Role created


πŸ”Ή STEP 4: Attach IAM Role to EC2

  1. EC2 β†’ Instances
  2. Select:
ec2-hands-on-1
  1. Actions β†’ Security
  2. Click Modify IAM role
  3. Select:
ec2-s3-read-role
  1. Save

πŸ“Œ Role attached without reboot


πŸ”Ή STEP 5: VERIFY ACCESS (NO ACCESS KEYS)

SSH into EC2:

ssh -i ec2-key-hands-on.pem ec2-user@ELASTIC_IP

Run:

aws s3 ls

πŸŽ‰ You should see S3 buckets list

πŸ“Œ No access key πŸ“Œ No secret key πŸ“Œ Fully secure


πŸ”Ή STEP 6: PROVE THERE ARE NO KEYS

Run:

cat ~/.aws/credentials

Output:

No such file or directory

βœ… Proof: IAM Role is working


🧠 HOW THIS WORKS INTERNALLY (INTERVIEW GOLD)

  • EC2 requests credentials from Metadata Service
  • IAM provides temporary credentials
  • Credentials auto-expire & rotate

🧠 INTERVIEW-READY ANSWER

IAM Roles provide secure, temporary credentials to EC2 instances, eliminating the need for hard-coded access keys. AWS automatically rotates these credentials, making IAM Roles the recommended and secure way to grant permissions to EC2.


⚠️ COMMON MISTAKES

❌ Using access keys on EC2 ❌ Over-permissioned roles ❌ One role for everything ❌ Not rotating credentials (keys)


βœ… LAB 24 TASK CHECKLIST

βœ” Created IAM Role βœ” Attached S3 Read policy βœ” Attached role to EC2 βœ” Accessed S3 without keys βœ” Understood security flow


πŸ§ͺ EC2 HANDS-ON – LAB 25

πŸ‘‰ EC2 Session Manager (Login WITHOUT SSH & Key Pair)

Image


🎯 Objective of LAB 25

By the end of this lab, you will:

  • Understand what Session Manager is
  • Access EC2 without SSH
  • Remove dependency on key pairs
  • Learn enterprise-grade secure access
  • Be interview + production ready

🧠 FIRST: What is Session Manager?

Session Manager is part of AWS Systems Manager

It allows you to: βœ” Connect to EC2 via AWS Console βœ” No SSH (port 22 not needed) βœ” No key pair βœ” Fully logged & auditable

Think like:

Session Manager = Secure remote terminal via AWS πŸ”


🧠 WHY Session Manager is BETTER than SSH?

SSHSession Manager
Needs port 22❌ No ports needed
Needs key pair❌ No keys
Hard to auditβœ… Fully logged
Security riskβœ… Very secure

πŸ‘‰ AWS RECOMMENDS Session Manager


🧠 PREREQUISITES (VERY IMPORTANT)

To use Session Manager, EC2 must have:

βœ” SSM Agent installed βœ” IAM Role attached with SSM permissions βœ” Internet access (or VPC endpoints)

Good news πŸŽ‰ Amazon Linux already has SSM Agent installed


πŸ”Ή STEP 1: Attach SSM IAM Role to EC2

We’ll extend the role you already used.

Open IAM Role

  1. IAM β†’ Roles
  2. Open:
ec2-s3-read-role

Attach SSM Policy

  1. Click Add permissions
  2. Attach policy:
AmazonSSMManagedInstanceCore
  1. Save

πŸ“Œ This policy allows:

  • Session Manager
  • Run Command
  • Patch Manager

πŸ”Ή STEP 2: Verify Role Attached to EC2

  1. EC2 β†’ Instances
  2. Select:
ec2-hands-on-1
  1. Security tab β†’ IAM role

It should show:

ec2-s3-read-role

πŸ”Ή STEP 3: Open Session Manager

  1. EC2 Console β†’ Instances
  2. Select your instance
  3. Click Connect
  4. Choose Session Manager
  5. Click Connect

πŸŽ‰ YOU ARE LOGGED IN

No: ❌ SSH ❌ Key pair ❌ Port 22


πŸ”Ή STEP 4: Verify Inside EC2

Inside Session Manager terminal, run:

whoami

Output:

ssm-user

πŸ“Œ This user is created dynamically by SSM

Check OS:

uname -a

πŸ”Ή STEP 5: PROVE SSH is NOT Needed (Concept)

You can:

  • Remove SSH rule from Security Group
  • EC2 still accessible via Session Manager

πŸ“Œ This is zero-attack-surface access

(Do NOT remove now β€” concept only)


🧠 HOW SESSION MANAGER WORKS (INTERVIEW GOLD)

  1. EC2 runs SSM Agent
  2. Agent talks to Systems Manager endpoint
  3. IAM Role authorizes access
  4. AWS Console opens secure tunnel

πŸ‘‰ No inbound traffic needed


🧠 INTERVIEW-READY ANSWER

EC2 Session Manager, part of AWS Systems Manager, provides secure shell access to instances without opening inbound ports or using SSH keys. It uses IAM roles and the SSM Agent, offering improved security and full auditing.


⚠️ COMMON MISTAKES

❌ No IAM role attached ❌ Missing SSM policy ❌ SSM Agent stopped ❌ No internet/VPC endpoint


βœ… LAB 25 TASK CHECKLIST

βœ” Added SSM policy βœ” Connected via Session Manager βœ” Logged in without SSH βœ” Understood secure access model


🏁 SECURITY ACCESS PHASE COMPLETED πŸŽ‰

You now know: βœ” SSH access βœ” Key pairs βœ” IAM Roles βœ” Session Manager (BEST PRACTICE)


πŸ§ͺ EC2 HANDS-ON – LAB 26

πŸ‘‰ Private EC2 + Bastion Host (Enterprise-Grade Secure Access)

Image

Image

Image

Image


🎯 Objective of LAB 26

By the end of this lab, you will:

  • Understand Public vs Private EC2
  • Create a Private EC2 instance
  • Use a Bastion Host for secure access
  • Learn enterprise security design
  • Be interview + production ready

🧠 FIRST: What is a Private EC2?

A Private EC2:

  • Has NO public IP
  • Lives in a private subnet
  • Cannot be accessed from the internet directly

Think like:

Private EC2 = Office server inside company network 🏒 Not exposed to the internet 🌐❌


🧠 What is a Bastion Host?

A Bastion Host:

  • Is a public EC2
  • Acts as a secure entry point
  • Used to access private EC2s

Think like:

Bastion = Security gate 🚧 Private EC2 = Internal room πŸ”


🧠 ARCHITECTURE WE ARE BUILDING

Your Laptop
   ↓
Bastion Host (Public Subnet)
   ↓
Private EC2 (Private Subnet)

This runs inside Amazon Web Services VPC


πŸ”Ή STEP 1: Understand Your VPC Structure

Go to:

  • VPC β†’ Subnets

You’ll see:

  • Public Subnet
  • Private Subnet

πŸ“Œ Public subnet:

  • Route to Internet Gateway

πŸ“Œ Private subnet:

  • NO Internet Gateway route

πŸ”Ή STEP 2: Launch BASTION HOST (Public EC2)

Launch new EC2

  • Name:
bastion-host
  • AMI: Amazon Linux 2023

  • Instance type: t2.micro

  • Subnet: Public Subnet

  • Auto-assign Public IP: Enabled

  • Security Group:

    • SSH (22) β†’ My IP only

Launch instance


πŸ”Ή STEP 3: Launch PRIVATE EC2

Launch another EC2

  • Name:
private-ec2
  • AMI: Amazon Linux 2023

  • Instance type: t2.micro

  • Subnet: Private Subnet

  • Auto-assign Public IP: ❌ Disabled

  • Security Group:

    • SSH (22) β†’ ONLY from Bastion SG

πŸ“Œ This EC2 has NO public IP


πŸ”Ή STEP 4: VERIFY PRIVATE EC2 IS NOT PUBLIC

Check EC2 details:

  • Public IPv4 address β†’ None

❌ Cannot SSH from laptop βœ… This is secure by design


πŸ”Ή STEP 5: CONNECT TO BASTION HOST

From your laptop:

ssh -i ec2-key-hands-on.pem ec2-user@BASTION_PUBLIC_IP

You are now inside the bastion host


πŸ”Ή STEP 6: COPY KEY TO BASTION (TEMPORARY)

⚠️ For learning only (not best practice)

On your laptop:

scp -i ec2-key-hands-on.pem ec2-key-hands-on.pem ec2-user@BASTION_PUBLIC_IP:/home/ec2-user/

On bastion:

chmod 400 ec2-key-hands-on.pem

πŸ”Ή STEP 7: CONNECT TO PRIVATE EC2 FROM BASTION

From inside bastion:

ssh -i ec2-key-hands-on.pem ec2-user@PRIVATE_EC2_PRIVATE_IP

πŸŽ‰ You are now logged into PRIVATE EC2


🧠 VERY IMPORTANT SECURITY RULE

❌ Never expose private EC2 to internet βœ” Access only via bastion / Session Manager βœ” Bastion SSH restricted to your IP


🧠 REAL-WORLD BEST PRACTICE (INTERVIEW GOLD)

PracticeStatus
Bastion in public subnetβœ…
Private EC2 no public IPβœ…
SSH only via bastionβœ…
IAM + Session Manager⭐ BEST

πŸ‘‰ Modern replacement: Bastion ❌ β†’ Session Manager βœ…


🧠 INTERVIEW-READY ANSWER

A Bastion Host is a publicly accessible EC2 instance used as a secure gateway to access private EC2 instances in a VPC. Private instances have no public IP and are protected from direct internet access, improving security.


⚠️ COMMON MISTAKES

❌ Giving public IP to private EC2 ❌ Opening SSH to 0.0.0.0/0 ❌ Storing keys on bastion permanently ❌ Using bastion when Session Manager is available


βœ… LAB 26 TASK CHECKLIST

βœ” Understood public vs private EC2 βœ” Launched bastion host βœ” Launched private EC2 βœ” Accessed private EC2 securely βœ” Learned enterprise network design


πŸ§ͺ EC2 HANDS-ON – LAB 27

πŸ‘‰ EC2 in Public vs Private Subnet (Traffic Flow & Internet Access)

Image

Image

Image

Image


🎯 Objective of LAB 27

By the end of this lab, you will:

  • Clearly understand Public vs Private Subnet
  • Know why an EC2 has or doesn’t have internet
  • Understand Internet Gateway (IGW) and NAT Gateway
  • Be able to draw & explain traffic flow (interview-ready)

🧠 FIRST: What is a Subnet? (Simple)

A Subnet is:

  • A range of IP addresses
  • Inside a VPC
  • Placed in one Availability Zone

Think like:

VPC = Building 🏒 Subnet = Floor 🧱


🧠 KEY RULE (MEMORIZE THIS)

❗ Subnet is NOT public or private by itself

A subnet becomes:

  • Public β†’ if its route table points to an Internet Gateway
  • Private β†’ if it does NOT point to an Internet Gateway

πŸ”Ή COMPONENTS YOU MUST KNOW

🌐 Internet Gateway (IGW)

  • Allows internet ↔ VPC
  • Required for public internet access

πŸ” NAT Gateway

  • Allows private EC2 β†’ internet
  • Blocks internet β†’ private EC2

πŸ”Ή STEP 1: Open Your VPC Route Tables

  1. AWS Console β†’ VPC

  2. Left menu β†’ Route Tables

  3. Identify:

    • Public route table
    • Private route table

πŸ”Ή STEP 2: Examine PUBLIC Subnet Route Table

Select public route table β†’ Routes tab

You will see something like:

DestinationTarget
10.0.0.0/16local
0.0.0.0/0igw-xxxx

πŸ“Œ Meaning:

  • Local VPC traffic β†’ allowed
  • All internet traffic β†’ Internet Gateway

πŸ‘‰ This makes the subnet PUBLIC


πŸ”Ή STEP 3: Examine PRIVATE Subnet Route Table

Select private route table β†’ Routes tab

You’ll see:

DestinationTarget
10.0.0.0/16local

πŸ“Œ Meaning:

  • Internal VPC traffic only
  • ❌ No internet access

πŸ‘‰ This makes the subnet PRIVATE


πŸ”Ή STEP 4: WHY Public EC2 Has Internet

Your Bastion Host:

  • In public subnet
  • Has public IP
  • Route β†’ IGW

Traffic flow:

Laptop β†’ IGW β†’ Public EC2
Public EC2 β†’ IGW β†’ Internet

πŸ”Ή STEP 5: WHY Private EC2 Has NO Internet

Your private EC2:

  • In private subnet
  • ❌ No public IP
  • ❌ No IGW route

Traffic flow:

Internet βŒβ†’ Private EC2

βœ” Secure by default


πŸ”Ή STEP 6: Give INTERNET to Private EC2 (OUTBOUND ONLY)

This is where NAT Gateway is used.

NAT Gateway flow:

Private EC2 β†’ NAT Gateway β†’ IGW β†’ Internet
Internet βŒβ†’ Private EC2

πŸ“Œ Used for:

  • OS updates
  • Package installs
  • API calls

πŸ”Ή STEP 7: REAL-WORLD ARCHITECTURE

Users
 ↓
Internet Gateway
 ↓
Public Subnet (ALB, Bastion)
 ↓
Private Subnet (EC2, App, DB)
 ↓
NAT Gateway β†’ Internet (outbound only)

Used by Amazon Web Services best practices


🧠 INTERVIEW-READY COMPARISON TABLE

FeaturePublic SubnetPrivate Subnet
IGW routeβœ… Yes❌ No
Public IPβœ… Yes❌ No
Internet accessβœ… Yes❌ No
Inbound from internetβœ… Possible❌ Blocked
Use caseALB, BastionApp, DB

🧠 INTERVIEW-READY ANSWER (VERY IMPORTANT)

A public subnet has a route to an Internet Gateway, allowing internet access, while a private subnet does not. Private instances can still access the internet outbound using a NAT Gateway, without being exposed to inbound traffic.


⚠️ COMMON MISTAKES

❌ Thinking β€œpublic subnet” = public IP ❌ Attaching IGW to private subnet ❌ Exposing databases publicly ❌ Forgetting NAT for updates


βœ… LAB 27 TASK CHECKLIST

βœ” Inspected route tables βœ” Understood IGW role βœ” Understood NAT Gateway role βœ” Explained traffic flow clearly βœ” Interview-level clarity achieved


πŸ§ͺ EC2 HANDS-ON – LAB 28

πŸ‘‰ Patch Management for EC2 (Automatic OS Updates – Secure & Scalable)

Image

Image

Image

Image


🎯 Objective of LAB 28

By the end of this lab, you will:

  • Understand why patching is critical
  • Use AWS Patch Manager
  • Patch EC2 without SSH
  • View patch compliance
  • Be production + interview ready

🧠 FIRST: What is Patch Management? (Simple)

Patch Management means:

  • Updating OS packages
  • Fixing security vulnerabilities
  • Applying bug fixes

Think like:

Patching = Regular medical check-up for servers 🩺

❌ Unpatched servers = security risk βœ… Patched servers = safe & compliant


🧠 WHICH AWS SERVICE DOES PATCHING?

Patching is handled by AWS Systems Manager (specifically Patch Manager)


🧠 WHY USE PATCH MANAGER (NOT MANUAL SSH)?

Manual SSHPatch Manager
Error-proneAutomated
No auditFull audit
Not scalableScales to 1000s EC2
Needs SSH❌ No SSH

πŸ‘‰ Production always uses Patch Manager


🧠 PREREQUISITES (YOU ALREADY HAVE THEM βœ…)

Your EC2 already has: βœ” SSM Agent βœ” IAM Role with AmazonSSMManagedInstanceCore βœ” Connectivity to SSM

So we’re ready πŸŽ‰


πŸ”Ή STEP 1: Open Patch Manager

  1. AWS Console β†’ Systems Manager
  2. Left menu β†’ Patch Manager

πŸ”Ή STEP 2: Check Managed Instances

  1. Systems Manager β†’ Fleet Manager
  2. Click Managed nodes

You should see your EC2:

ec2-hands-on-1

πŸ“Œ If EC2 is visible β†’ SSM is working


πŸ”Ή STEP 3: Patch Compliance (Read-Only View)

  1. Systems Manager β†’ Patch Manager
  2. Click Compliance

You’ll see:

  • Missing patches
  • Installed patches
  • Compliance status

πŸ“Œ This gives security visibility


πŸ”Ή STEP 4: Create Patch Baseline (Concept)

AWS provides default patch baselines:

  • Amazon Linux
  • Ubuntu
  • Windows

πŸ“Œ We’ll use default baseline (best practice)


πŸ”Ή STEP 5: Run Patch Scan (SAFE – NO CHANGES)

We’ll first SCAN, not install.

  1. Patch Manager β†’ Patches

  2. Click Configure patching

  3. Choose:

    • Patch operation β†’ Scan
    • Instances β†’ select your EC2
  4. Run

πŸ“Œ Scan:

  • Checks missing patches
  • Does NOT install anything

πŸ”Ή STEP 6: View Scan Results

After completion:

  • Status β†’ Success
  • Compliance β†’ Compliant / Non-compliant

πŸ“Œ This is used by security teams


πŸ”Ή STEP 7: Install Patches (Conceptual – IMPORTANT)

In production:

  • Patch operation β†’ Install
  • Scheduled during maintenance window
  • Automatic reboot (optional)

⚠️ We won’t install now to avoid downtime But concept is VERY important


πŸ”Ή STEP 8: Maintenance Window (Concept)

A Maintenance Window:

  • Defines WHEN patching happens

  • Example:

    • Sunday 2 AM – 4 AM

Used for:

  • Patching
  • Reboots
  • Updates

πŸ“Œ Zero impact on users


🧠 REAL-WORLD PATCH STRATEGY

βœ” Scan daily βœ” Patch weekly βœ” Patch in maintenance window βœ” Auto reboot if needed βœ” Monitor compliance


🧠 INTERVIEW-READY ANSWER

AWS Patch Manager, part of Systems Manager, automates the process of scanning and installing OS patches on EC2 instances. It ensures security compliance without requiring SSH access and supports scheduling through maintenance windows.


⚠️ COMMON MISTAKES

❌ Manual patching via SSH ❌ No maintenance window ❌ Patching production during peak hours ❌ No compliance monitoring


βœ… LAB 28 TASK CHECKLIST

βœ” Opened Patch Manager βœ” Verified managed EC2 βœ” Ran patch scan βœ” Viewed compliance βœ” Understood production patching strategy


πŸ§ͺ EC2 HANDS-ON – LAB 29

πŸ‘‰ EC2 Backup Strategy (Snapshots, AMIs & Automation)

Image

Image

Image


🎯 Objective of LAB 29

By the end of this lab, you will:

  • Design a complete EC2 backup strategy
  • Use EBS Snapshots correctly
  • Use AMIs for full server backup
  • Understand backup automation
  • Be interview + production ready

🧠 FIRST: Why Backup is CRITICAL

Failures happen:

  • Human error ❌
  • AZ outage ❌
  • Accidental delete ❌
  • Security incident ❌

Think like:

Backup = Insurance for your data πŸ›‘οΈ


🧠 TYPES OF EC2 BACKUPS (VERY IMPORTANT)

1️⃣ EBS Snapshots

  • Backup of data disks
  • Incremental
  • Fast restore

2️⃣ AMIs

  • Backup of entire EC2
  • OS + software + config
  • Used to recreate servers

3️⃣ Automated Backups

  • Scheduled
  • No manual effort
  • Required in production

πŸ”Ή BACKUP STRATEGY (REAL-WORLD STANDARD)

WhatBackup Method
OS + AppAMI
App dataEBS Snapshot
LogsCloudWatch / S3
DRCross-region copy

πŸ”Ή STEP 1: Identify What to Back Up

For ec2-hands-on-1:

βœ” Root volume β†’ OS βœ” /data EBS β†’ App data βœ” Config β†’ AMI

πŸ“Œ Never rely on one backup type


πŸ”Ή STEP 2: On-Demand EBS Snapshot (Recap)

  1. EC2 β†’ Volumes
  2. Select data volume
  3. Actions β†’ Create snapshot
  4. Name:
daily-data-backup

πŸ“Œ Use before:

  • App upgrade
  • OS patch
  • Major change

πŸ”Ή STEP 3: AMI as Full Server Backup

  1. EC2 β†’ Instances
  2. Select ec2-hands-on-1
  3. Actions β†’ Image and templates
  4. Create image

Name:

ec2-backup-ami-v2

πŸ“Œ This captures:

  • Root EBS
  • Config
  • Installed software

πŸ”Ή STEP 4: AUTOMATED BACKUP (IMPORTANT CONCEPT)

In production, backups are NOT manual.

AWS provides AWS Backup to: βœ” Schedule backups βœ” Retention rules βœ” Cross-region copy βœ” Compliance reports


πŸ”Ή STEP 5: AWS Backup – How It Works (Concept)

  1. Create Backup Plan

  2. Define:

    • Schedule (daily / weekly)
    • Retention (7 days / 30 days)
  3. Assign:

    • EC2
    • EBS volumes
  4. AWS runs backups automatically

πŸ“Œ Zero manual effort


πŸ”Ή STEP 6: Restore Strategy (MOST IMPORTANT)

Backup is useless without restore testing.

Restore Options:

  • Snapshot β†’ New EBS
  • AMI β†’ New EC2
  • Cross-region snapshot β†’ DR EC2

πŸ“Œ Always test restore


🧠 REAL-WORLD BACKUP POLICY (EXAMPLE)

BackupFrequencyRetention
EBS SnapshotDaily7 days
AMIWeekly4 weeks
Cross-regionWeekly4 weeks

🧠 INTERVIEW-READY ANSWER

A robust EC2 backup strategy uses EBS snapshots for data volumes and AMIs for full server recovery. Backups should be automated using AWS Backup with defined schedules, retention policies, and regular restore testing.


⚠️ COMMON MISTAKES

❌ Only AMI, no data snapshot ❌ Manual backups ❌ No retention policy ❌ No restore testing ❌ Same-region backups only


βœ… LAB 29 TASK CHECKLIST

βœ” Identified backup scope βœ” Created snapshot βœ” Created AMI βœ” Understood AWS Backup βœ” Designed restore strategy


πŸ§ͺ EC2 HANDS-ON – LAB 30

πŸ‘‰ EC2 Security Best Practices (Hardening & Real Threat Protection)

Image

Image

Image

Image


🎯 Objective of LAB 30

By the end of this lab, you will:

  • Understand real EC2 security threats
  • Apply hardening best practices
  • Reduce attack surface
  • Know what AWS secures vs what YOU secure
  • Be 100% interview + production ready

🧠 FIRST: AWS Shared Responsibility Model (CRITICAL)

Security in AWS is shared.

AWS is responsible for:

  • Data center security
  • Hardware
  • Physical network
  • Hypervisor

YOU are responsible for:

  • EC2 OS security
  • Security Groups
  • IAM
  • Patching
  • Application security

πŸ“Œ This model applies to Amazon Web Services


🧠 REAL EC2 THREATS (MUST KNOW)

ThreatExample
Open SSH0.0.0.0/0 on port 22
Key leakage.pem in GitHub
Unpatched OSExploits
Public servicesDB exposed
Over-permissionIAM * access

πŸ”Ή STEP 1: LOCK DOWN SSH (HANDS-ON CHECK)

Go to: EC2 β†’ Security Groups β†’ Instance SG

Ensure:

SSH (22) β†’ My IP only

❌ Never:

0.0.0.0/0

πŸ“Œ This alone blocks 90% attacks


πŸ”Ή STEP 2: REMOVE SSH COMPLETELY (BEST PRACTICE)

If using Session Manager:

  • Remove SSH rule entirely
  • No port 22 open

πŸ“Œ Zero inbound access = zero attack surface


πŸ”Ή STEP 3: USE IAM ROLES (NO KEYS)

βœ” IAM Role attached βœ” No access keys stored βœ” Temporary credentials

You already implemented this in LAB 24 βœ…


πŸ”Ή STEP 4: OS HARDENING (IMPORTANT)

On EC2:

sudo dnf update -y

πŸ“Œ Always:

  • Patch OS
  • Use Patch Manager (LAB 28)

πŸ”Ή STEP 5: MINIMIZE INSTALLED SOFTWARE

❌ Remove unused packages βœ” Only required services running

Check running services:

systemctl list-units --type=service

πŸ”Ή STEP 6: SECURITY GROUP BEST PRACTICES

RuleBest Practice
InboundMinimal
OutboundRestrict if possible
PortsOnly required
SourceKnown IP / SG

πŸ“Œ SG = First firewall


πŸ”Ή STEP 7: NETWORK SECURITY LAYERS (DEFENSE IN DEPTH)

Internet
 ↓
Security Group
 ↓
NACL
 ↓
OS Firewall
 ↓
Application Security

πŸ“Œ Multiple layers = stronger security


πŸ”Ή STEP 8: ENABLE LOGGING & MONITORING

βœ” CloudWatch Metrics βœ” CloudWatch Logs βœ” Alarms

You already implemented this in:

  • LAB 21
  • LAB 23

πŸ”Ή STEP 9: TAGGING FOR SECURITY & AUDIT

Add tags:

Environment = Prod
Owner = DevOps
Critical = Yes

πŸ“Œ Helps:

  • Audits
  • Cost tracking
  • Automation

πŸ”Ή STEP 10: BACKUP + DR (SECURITY TOO)

βœ” Snapshots βœ” AMIs βœ” Restore testing

Security is incomplete without recovery


🧠 REAL-WORLD SECURITY CHECKLIST (SAVE THIS)

βœ” No public DB βœ” No SSH open βœ” IAM roles only βœ” Patch regularly βœ” Monitor continuously βœ” Backup tested


🧠 INTERVIEW-READY ANSWER (VERY IMPORTANT)

EC2 security is achieved through defense in depth, including restrictive security groups, IAM roles instead of access keys, regular patching via Systems Manager, centralized logging with CloudWatch, and secure access using Session Manager.


⚠️ COMMON SECURITY MISTAKES

❌ SSH open to world ❌ Hardcoded credentials ❌ No monitoring ❌ No backups ❌ Over-permissioned IAM


βœ… LAB 30 TASK CHECKLIST

βœ” Understood shared responsibility βœ” Identified real threats βœ” Applied hardening best practices βœ” Reduced attack surface βœ” Interview-ready security knowledge


🏁 SECURITY PHASE COMPLETED πŸŽ‰

You have mastered: βœ… Access security βœ… Network security βœ… OS security βœ… Monitoring βœ… Backup & recovery


πŸ§ͺ EC2 HANDS-ON – LAB 31

πŸ‘‰ EC2 Pricing & Cost Optimization (Save MONEY like a Pro πŸ’°)

Image

Image

Image

Image


🎯 Objective of LAB 31

By the end of this lab, you will:

  • Understand how EC2 pricing works
  • Learn all EC2 pricing models
  • Know when to use each model
  • Apply real cost-optimization techniques
  • Be interview + production ready

🧠 FIRST: How AWS Charges for EC2 (Simple)

AWS charges EC2 based on:

  • Instance type (CPU, RAM)
  • Time used (per second/minute)
  • Storage (EBS)
  • Data transfer
  • Extra services (ELB, NAT, snapshots)

Think like:

EC2 = Rent for a virtual server 🏠


🧠 EC2 PRICING MODELS (MUST KNOW)

1️⃣ On-Demand Instances

What it is

  • Pay as you go
  • No commitment

Use when

  • Learning
  • Testing
  • Short-term workloads

Pros βœ” Flexible βœ” No upfront cost

Cons ❌ Most expensive


2️⃣ Reserved Instances (RI)

What it is

  • 1-year or 3-year commitment
  • Big discount

Use when

  • Steady workloads
  • Production systems

Savings πŸ’° Up to 72%

Types

  • Standard RI
  • Convertible RI

3️⃣ Savings Plans (MODERN & IMPORTANT)

What it is

  • Commit to $ per hour
  • Flexible across instance types

Use when

  • Long-running apps
  • Microservices

πŸ“Œ AWS recommends Savings Plans over RIs


4️⃣ Spot Instances (VERY IMPORTANT)

What it is

  • Use spare AWS capacity
  • Very cheap

Savings πŸ’° Up to 90%

Risk ❌ Can be terminated anytime

Use when

  • Batch jobs
  • CI/CD
  • Big data processing

🧠 QUICK INTERVIEW TABLE

ModelCostRiskUse Case
On-DemandHighNoneDev/Test
ReservedLowLowProd
Savings PlanLowLowProd
SpotVery LowHighBatch

πŸ”Ή STEP 1: View EC2 Pricing in Console

  1. AWS Console β†’ EC2
  2. Click Instance types
  3. Select t2.micro
  4. Click Pricing

πŸ“Œ Pricing varies by:

  • Region
  • OS

πŸ”Ή STEP 2: Check Your CURRENT COST

  1. AWS Console β†’ Billing

  2. Open Cost Explorer

  3. Filter:

    • Service β†’ EC2
    • Time β†’ Last 7 days

πŸ“Œ This shows real money usage


πŸ”Ή STEP 3: IDENTIFY COST WASTAGE (REAL WORLD)

Look for: ❌ Stopped but attached EBS ❌ Unused Elastic IPs ❌ Oversized instances ❌ Idle EC2s


πŸ”Ή STEP 4: INSTANCE RIGHT-SIZING (IMPORTANT)

Use:

  • CloudWatch CPU metrics

Example:

  • CPU < 10% always ❌ β†’ Instance is oversized

Solution:

  • Move from t3.large β†’ t3.micro

πŸ“Œ Saves money immediately


πŸ”Ή STEP 5: AUTO SCALING = COST SAVER

βœ” Scale out only when needed βœ” Scale in during low traffic

You already implemented this in LAB 19 & 22


πŸ”Ή STEP 6: SPOT INSTANCES (CONCEPTUAL)

In ASG:

  • Mix:

    • On-Demand (base)
    • Spot (extra capacity)

πŸ“Œ Production-grade cost optimization


πŸ”Ή STEP 7: SCHEDULE STOP/START (HUGE SAVINGS)

For non-prod:

  • Stop EC2 at night
  • Start in morning

Can save: πŸ’° 60–70% monthly

Use:

  • EventBridge
  • Lambda
  • SSM Automation

🧠 REAL-WORLD COST OPTIMIZATION CHECKLIST

βœ” Use right instance size βœ” Use Savings Plans βœ” Auto Scaling enabled βœ” Use Spot for batch βœ” Delete unused resources βœ” Monitor monthly bill


🧠 INTERVIEW-READY ANSWER

EC2 cost optimization involves selecting the appropriate pricing model such as On-Demand, Reserved Instances, Savings Plans, or Spot Instances, combined with right-sizing, Auto Scaling, and continuous monitoring using Cost Explorer and CloudWatch.


⚠️ COMMON COST MISTAKES

❌ Leaving EC2 running unused ❌ Ignoring EBS & snapshots ❌ No Auto Scaling ❌ No cost monitoring


βœ… LAB 31 TASK CHECKLIST

βœ” Understood pricing models βœ” Checked EC2 pricing βœ” Viewed Cost Explorer βœ” Identified cost wastage βœ” Learned optimization strategies


πŸ§ͺ EC2 HANDS-ON – LAB 32

πŸ‘‰ Spot Instances (Ultra-Low Cost EC2 + Risk Handling)

Image

Image

Image


🎯 Objective of LAB 32

By the end of this lab, you will:

  • Understand what Spot Instances are
  • Launch a Spot EC2
  • Handle interruption safely
  • Use Spot with Auto Scaling
  • Be interview + production ready

🧠 FIRST: What is a Spot Instance? (Simple Words)

A Spot Instance:

  • Uses unused EC2 capacity
  • Is very cheap
  • Can be stopped by AWS anytime

Think like:

Spot = Traveling in empty train seats πŸš† Cheap, but seat may be taken back

Spot is part of Amazon Web Services EC2 pricing


🧠 WHY Spot is SO CHEAP?

AWS sells:

  • Spare capacity
  • With no guarantee

πŸ’° Savings:

  • Up to 90% cheaper than On-Demand

🧠 THE BIG RISK (MUST KNOW)

❗ Spot instances can be:

  • Interrupted with 2-minute warning
  • Terminated or stopped

πŸ‘‰ Never use Spot alone for critical apps


πŸ”Ή WHEN TO USE SPOT (REAL USE CASES)

βœ” Batch processing βœ” CI/CD builds βœ” Big data jobs βœ” Auto Scaling extra capacity βœ” Non-critical workloads

❌ NOT for:

  • Databases
  • Single EC2 prod apps
  • Stateful services

πŸ”Ή STEP 1: Launch a Spot Instance (Hands-On)

  1. EC2 β†’ Launch instance
  2. Name:
ec2-spot-demo

Instance Details

  • AMI β†’ Amazon Linux 2023
  • Instance type β†’ t3.micro
  • Key pair β†’ existing

Advanced Details (IMPORTANT)

Scroll to Advanced details

  • Purchasing option β†’ Spot
  • Spot instance type β†’ One-time
  • Interruption behavior β†’ Terminate
  • Max price β†’ Leave empty (recommended)

πŸ“Œ AWS will pick cheapest available Spot


Security Group

  • SSH (22) β†’ My IP
  • HTTP (80) β†’ Anywhere

Launch Instance

Click Launch instance


πŸ”Ή STEP 2: Verify Spot Instance

  1. EC2 β†’ Instances
  2. Select instance
  3. Check:
Instance lifecycle β†’ Spot

πŸŽ‰ You are running a Spot EC2


πŸ”Ή STEP 3: Spot Interruption Notice (CRITICAL)

AWS provides:

2-minute warning

Available at:

http://169.254.169.254/latest/meta-data/spot/instance-action

πŸ”Ή STEP 4: CHECK INTERRUPTION (Hands-On)

SSH into Spot EC2:

ssh -i ec2-key-hands-on.pem ec2-user@SPOT_PUBLIC_IP

Run:

curl http://169.254.169.254/latest/meta-data/spot/instance-action

Output:

  • Empty β†’ No interruption
  • JSON β†’ Interruption coming

πŸ“Œ This endpoint is very important for automation


πŸ”Ή STEP 5: HANDLE INTERRUPTION SAFELY (CONCEPT)

In real systems:

  • Save work to S3
  • Send logs to CloudWatch
  • Gracefully stop job

Example logic:

If interruption notice:
 β†’ checkpoint work
 β†’ upload results
 β†’ exit cleanly

πŸ”Ή STEP 6: Spot with Auto Scaling (BEST PRACTICE)

In production:

  • Use Mixed Instance Policy

  • Combine:

    • On-Demand (base)
    • Spot (extra capacity)

πŸ“Œ If Spot is interrupted:

  • ASG replaces it automatically

🧠 INTERVIEW-READY COMPARISON

FeatureOn-DemandSpot
PriceHighVery Low
ReliabilityHighMedium
Interruption❌ Noβœ… Yes
Use caseProdBatch / ASG

🧠 INTERVIEW-READY ANSWER

Spot Instances allow customers to use spare EC2 capacity at significantly reduced prices, with the trade-off that instances can be interrupted with a two-minute warning. They are ideal for fault-tolerant and stateless workloads.


⚠️ COMMON MISTAKES

❌ Using Spot for databases ❌ No checkpointing ❌ No ASG fallback ❌ Expecting 24/7 availability


βœ… LAB 32 TASK CHECKLIST

βœ” Launched Spot EC2 βœ” Verified Spot lifecycle βœ” Checked interruption endpoint βœ” Understood risk handling βœ” Learned cost-saving strategy


πŸ§ͺ EC2 HANDS-ON – LAB 33

πŸ‘‰ Instance Right-Sizing (Performance βš–οΈ Cost Balance)

Image

Image

Image

Image


🎯 Objective of LAB 33

By the end of this lab, you will:

  • Understand what right-sizing really means
  • Use CloudWatch metrics to detect waste
  • Learn how to choose the correct instance type
  • Know AWS Compute Optimizer
  • Be interview + production ready

🧠 FIRST: What is Instance Right-Sizing?

Right-sizing means:

  • Choosing the smallest EC2 instance
  • That still delivers required performance

Think like:

Don’t use a truck 🚚 to carry a backpack πŸŽ’


🧠 WHY Right-Sizing is IMPORTANT?

❌ Oversized instance β†’ Money waste ❌ Undersized instance β†’ Performance issues

βœ” Right-sized β†’ Optimal cost + performance


πŸ”Ή STEP 1: Identify a Candidate EC2

Pick:

  • ec2-hands-on-1 or
  • Any EC2 from your Auto Scaling Group

πŸ”Ή STEP 2: Analyze CPU Utilization (MOST IMPORTANT)

  1. Open CloudWatch
  2. Go to Metrics β†’ EC2 β†’ Per-Instance Metrics
  3. Select CPUUtilization

Look at:

  • Last 7–14 days
  • Average CPU %

Decision Rule (SAVE THIS)

CPU UsageMeaning
< 10%❌ Over-provisioned
10–40%βœ… Right-sized
> 70%❌ Under-provisioned

πŸ”Ή STEP 3: Analyze Memory (IMPORTANT CONCEPT)

⚠️ EC2 does NOT send memory metrics by default.

To monitor memory:

  • Install CloudWatch Agent
  • Send memory metrics

πŸ“Œ In production, CPU alone is not enough


πŸ”Ή STEP 4: Check Network & Disk Metrics

Also check:

  • NetworkIn / NetworkOut
  • DiskReadOps / DiskWriteOps

πŸ“Œ If all metrics are low β†’ instance is oversized


πŸ”Ή STEP 5: Example Right-Sizing Decision

Current setup:

t3.large
CPU avg = 8%

Better option:

t3.micro or t3.small

πŸ’° Savings:

  • Up to 70% monthly

πŸ”Ή STEP 6: Use AWS Compute Optimizer (BEST PRACTICE)

AWS provides AWS Compute Optimizer

What it does:

βœ” Analyzes EC2 usage βœ” Recommends better instance types βœ” Uses machine learning


How to Check:

  1. AWS Console β†’ Compute Optimizer
  2. Enable it (one-time)
  3. Go to EC2 recommendations

πŸ“Œ This is enterprise-grade optimization


πŸ”Ή STEP 7: Right-Sizing with Auto Scaling (BEST)

Instead of one big EC2:

  • Use smaller instances
  • Scale horizontally with ASG

Example:

1 Γ— t3.large ❌
3 Γ— t3.micro βœ…

βœ” Cheaper βœ” More resilient


🧠 INTERVIEW-READY ANSWER

Instance right-sizing involves analyzing CloudWatch metrics such as CPU, memory, and network usage to select the most cost-effective EC2 instance type without compromising performance. AWS Compute Optimizer can automate recommendations using machine learning.


⚠️ COMMON MISTAKES

❌ Right-sizing based on CPU only ❌ Ignoring peak usage ❌ No monitoring after resizing ❌ Manual guesses instead of data


βœ… LAB 33 TASK CHECKLIST

βœ” Analyzed CPU utilization βœ” Understood over vs under sizing βœ” Learned memory monitoring concept βœ” Used Compute Optimizer (conceptually) βœ” Learned cost-performance balance


πŸ§ͺ EC2 HANDS-ON – LAB 34

πŸ‘‰ Free Tier Safety & Cleanup (Avoid Billing Surprises)

Image

Image

Image

Image


🎯 Objective of LAB 34

By the end of this lab, you will:

  • Know exact EC2 Free Tier limits
  • Identify hidden cost traps
  • Clean up unused resources safely
  • Set billing alerts
  • Be 100% safe from surprise bills

🧠 FIRST: What Does EC2 Free Tier REALLY Give?

Under **Amazon Web Services Free Tier (12 months):

EC2 Compute

βœ” 750 hours / month

  • t2.micro or t3.micro
  • Linux or Windows

πŸ“Œ 1 instance Γ— 24 Γ— 30 β‰ˆ 720 hours πŸ‘‰ Only ONE instance should run continuously


EBS Storage

βœ” 30 GB total

  • Root + additional volumes combined

Snapshots

βœ” 1 GB free ❌ Extra snapshots = charged


Data Transfer

βœ” 15 GB outbound / month ❌ More = charged


🧠 MOST COMMON BILLING TRAPS (READ CAREFULLY)

TrapWhy Cost Happens
Multiple EC2 runningHours exceed 750
Unused EBS volumesCharged even if EC2 stopped
Elastic IP not attachedCharged
NAT GatewayAlways paid ❌
Load BalancerCharged hourly ❌
Old snapshotsStorage cost
Stopped EC2EBS still billed

πŸ”Ή STEP 1: CHECK WHAT IS CURRENTLY RUNNING

Go to:

  • EC2 β†’ Instances

Action:

  • Keep only 1 required EC2
  • Stop or terminate others

πŸ“Œ Recommendation:

  • Keep ec2-hands-on-1
  • Stop learning/test EC2s

πŸ”Ή STEP 2: CLEAN UP LOAD BALANCER (IMPORTANT)

  1. EC2 β†’ Load Balancers
  2. Delete:
alb-ec2-hands-on

πŸ“Œ ALB is NOT free tier


πŸ”Ή STEP 3: CLEAN UP AUTO SCALING

  1. EC2 β†’ Auto Scaling Groups
  2. Delete:
asg-ec2-hands-on

πŸ“Œ This also terminates ASG EC2s


πŸ”Ή STEP 4: DELETE UNUSED EBS VOLUMES

  1. EC2 β†’ Volumes
  2. Delete:
  • Volumes not attached to any EC2
  • Old test volumes

πŸ“Œ Look for:

State: available

πŸ”Ή STEP 5: DELETE OLD SNAPSHOTS

  1. EC2 β†’ Snapshots
  2. Delete:
  • Test snapshots
  • Old backups you don’t need

πŸ“Œ Snapshots accumulate cost silently


πŸ”Ή STEP 6: RELEASE UNUSED ELASTIC IPs

  1. EC2 β†’ Elastic IPs
  2. If any EIP is:
Not associated

β†’ Release it

πŸ“Œ Unattached EIP = charged


πŸ”Ή STEP 7: CHECK NAT GATEWAY (CRITICAL)

  1. VPC β†’ NAT Gateways
  2. If exists β†’ DELETE

⚠️ NAT Gateway is expensive (~β‚Ή3–4 per hour)


πŸ”Ή STEP 8: SET BILLING ALERT (MUST DO)

Enable Billing Alerts

  1. Billing β†’ Billing preferences
  2. Enable:
Receive Billing Alerts

Create Budget Alert

  1. Billing β†’ Budgets
  2. Create budget:
Monthly cost budget = $5
  1. Email notification β†’ Your email

πŸ“Œ You’ll get alert before bill increases


βœ” 1 EC2 (t2/t3.micro) βœ” No ALB βœ” No NAT Gateway βœ” Minimal EBS (≀ 30 GB) βœ” Stop EC2 when not needed


🧠 INTERVIEW-READY ANSWER

To stay within the EC2 Free Tier, I monitor running hours, clean up unused EBS volumes, snapshots, Elastic IPs, and disable paid services like Load Balancers and NAT Gateways. I also configure AWS Budgets and billing alerts to avoid unexpected charges.


⚠️ FINAL WARNING (IMPORTANT)

AWS will NOT stop services automatically Responsibility is yours

πŸ‘‰ This lab saves real money πŸ’°


βœ… LAB 34 TASK CHECKLIST

βœ” Checked EC2 running hours βœ” Deleted ALB & ASG βœ” Cleaned EBS volumes βœ” Removed snapshots βœ” Released Elastic IPs βœ” Set billing alert


πŸ§ͺ EC2 HANDS-ON – LAB 35

πŸ‘‰ Production EC2 Architecture (End-to-End Real-World Setup)

Image

Image

Image

Image


🎯 Project Goal

Design and understand a secure, scalable, highly available, and cost-optimized EC2 production architecture β€” exactly what companies use.

By the end, you’ll be able to:

  • Design EC2 architecture from scratch
  • Explain every component confidently
  • Answer real interview system-design questions
  • Operate EC2 like a production engineer

πŸ—οΈ FINAL ARCHITECTURE (WHAT YOU BUILT)

Users
  ↓
Route 53 (DNS)
  ↓
Application Load Balancer (Multi-AZ, Public Subnets)
  ↓
Auto Scaling Group (Multi-AZ)
  ↓
EC2 Instances (Private Subnets)
  ↓
EBS (Persistent Storage)

Security & Ops:
- IAM Roles (no keys)
- Session Manager (no SSH)
- CloudWatch (metrics, logs, alarms)
- Patch Manager (automated updates)
- Backups (Snapshots + AMIs)

πŸ”Ή COMPONENT BREAKDOWN (REAL-WORLD VIEW)

1️⃣ VPC & Networking

  • Public Subnets

    • ALB
    • Bastion (optional / legacy)
  • Private Subnets

    • EC2 instances (no public IP)
  • Internet Gateway β†’ Internet access for ALB

  • NAT Gateway β†’ Outbound internet for private EC2 (optional in prod)

βœ… Result: No EC2 exposed to the internet


2️⃣ Compute Layer (EC2)

  • EC2 launched via Auto Scaling Group
  • Uses Golden AMI
  • Stateless design
  • Automatically replaced if unhealthy

βœ… Result: Self-healing compute layer


3️⃣ Load Balancing

  • Application Load Balancer
  • Multi-AZ
  • Health checks
  • Routes traffic only to healthy EC2s

βœ… Result: Zero-downtime traffic handling


4️⃣ Scaling

  • Auto Scaling Group
  • CloudWatch CPU metrics
  • Scale out during load
  • Scale in during low traffic

βœ… Result: Performance + cost efficiency


5️⃣ Security

  • IAM Roles (no access keys)
  • Session Manager (no SSH, no port 22)
  • Security Groups (least privilege)
  • Private subnets for EC2

βœ… Result: Enterprise-grade security


6️⃣ Monitoring & Logs

  • CloudWatch Metrics (CPU, Network)
  • CloudWatch Alarms (alerts, scaling)
  • CloudWatch Logs (Apache / app logs)

βœ… Result: Fast troubleshooting & observability


7️⃣ Patch Management

  • AWS Systems Manager Patch Manager
  • Scan & install patches
  • Maintenance windows

βœ… Result: Always-patched, compliant servers


8️⃣ Backup & Recovery

  • EBS Snapshots β†’ data backup
  • AMIs β†’ full server backup
  • Restore testing strategy

βœ… Result: Disaster-ready architecture


9️⃣ Cost Optimization

  • Right-sized instances
  • Auto Scaling
  • Spot instances (for non-critical workloads)
  • Billing alerts
  • Free-tier safety cleanup

βœ… Result: No surprise bills


🧠 INTERVIEW-READY SYSTEM DESIGN ANSWER (⭐ GOLD ⭐)

β€œI design EC2 architectures using a VPC with public and private subnets, place an Application Load Balancer in public subnets, and run EC2 instances in private subnets via Auto Scaling Groups across multiple Availability Zones. I use IAM roles instead of access keys, Session Manager instead of SSH, CloudWatch for monitoring, Systems Manager for patching, and EBS snapshots plus AMIs for backup. This ensures high availability, security, scalability, and cost efficiency.”


🧠 WHAT YOU HAVE MASTERED (BIG LIST)

βœ… EC2 fundamentals βœ… SSH, Key Pairs, Session Manager βœ… Security Groups & NACLs βœ… EBS, Snapshots, AMIs βœ… User Data automation βœ… Multi-AZ architecture βœ… Load Balancers βœ… Auto Scaling βœ… CloudWatch monitoring & alarms βœ… Logs & troubleshooting βœ… IAM roles & security βœ… Patch management βœ… Backup & DR βœ… Cost optimization βœ… Free tier safety βœ… Production EC2 architecture


πŸ§ͺ EC2 HANDS-ON – LAB 36

πŸ‘‰ Host a Full Web App (Frontend + Backend) on EC2

Image

Image

Image

Image


🎯 Objective of LAB 36

By the end of this lab, you will:

  • Deploy a real frontend + backend
  • Run backend on a custom port
  • Use Nginx as reverse proxy
  • Access the app via single public URL
  • Understand real-world EC2 app hosting

🧠 Architecture (What We Are Building)

Browser
  ↓
Nginx (Port 80)
  ↓
Backend API (Node.js – Port 3000)

πŸ“Œ Frontend served by Nginx πŸ“Œ Backend runs separately πŸ“Œ User never sees backend port


πŸ”Ή Tech Stack (Simple & Practical)

  • Frontend: Static HTML
  • Backend: Node.js (Express)
  • Web Server / Proxy: Nginx
  • Server: EC2 (Amazon Linux)

πŸ‘‰ This setup is very common in real companies


πŸ”Ή STEP 1: Use a CLEAN EC2 Instance

Use:

ec2-hands-on-1

Make sure:

  • Instance is running
  • Port 80 allowed in Security Group
  • You can connect via Session Manager or SSH

πŸ”Ή STEP 2: Install Required Software

Connect to EC2

ssh -i ec2-key-hands-on.pem ec2-user@PUBLIC_IP

Update OS

sudo dnf update -y

Install Node.js

sudo dnf install nodejs -y

πŸ“Œ nodejs β†’ runtime for backend πŸ“Œ Comes with npm

Verify:

node -v
npm -v

πŸ”Ή STEP 3: Create Backend Application

Create app folder

mkdir backend
cd backend

Initialize Node project

npm init -y

πŸ“Œ Creates package.json


Install Express

npm install express

Create Backend File

nano index.js

Paste this:

const express = require('express');
const app = express();

app.get('/api/hello', (req, res) => {
  res.json({ message: 'Hello from Backend API πŸš€' });
});

app.listen(3000, () => {
  console.log('Backend running on port 3000');
});

Save β†’ CTRL + X β†’ Y β†’ Enter


Run Backend

node index.js

You should see:

Backend running on port 3000

πŸ”Ή STEP 4: Test Backend Directly (Important)

Open browser:

http://PUBLIC_IP:3000/api/hello

Expected output:

{"message":"Hello from Backend API πŸš€"}

βœ… Backend works


πŸ”Ή STEP 5: Install & Configure Nginx (Frontend + Proxy)

Install Nginx

sudo dnf install nginx -y

Start & enable:

sudo systemctl start nginx
sudo systemctl enable nginx

πŸ”Ή STEP 6: Create Frontend Page

sudo nano /usr/share/nginx/html/index.html

Paste:

<!DOCTYPE html>
<html>
<head>
  <title>EC2 Full Stack App</title>
</head>
<body>
  <h1>Frontend on EC2 πŸŽ‰</h1>
  <button onclick="callApi()">Call Backend</button>
  <p id="result"></p>

  <script>
    function callApi() {
      fetch('/api/hello')
        .then(res => res.json())
        .then(data => {
          document.getElementById('result').innerText = data.message;
        });
    }
  </script>
</body>
</html>

Save & exit


πŸ”Ή STEP 7: Configure Nginx as Reverse Proxy (MOST IMPORTANT)

Edit config:

sudo nano /etc/nginx/conf.d/app.conf

Paste:

server {
    listen 80;

    location / {
        root /usr/share/nginx/html;
        index index.html;
    }

    location /api/ {
        proxy_pass http://localhost:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

Save & exit


Restart Nginx

sudo nginx -t
sudo systemctl restart nginx

πŸ“Œ nginx -t β†’ checks config (VERY IMPORTANT)


πŸ”Ή STEP 8: FINAL TEST (BIG MOMENT πŸŽ‰)

Open browser:

http://PUBLIC_IP

1️⃣ Frontend loads 2️⃣ Click Call Backend 3️⃣ You see:

Hello from Backend API πŸš€

πŸŽ‰ FULL STACK APP IS LIVE ON EC2


🧠 REAL-WORLD LEARNING (IMPORTANT)

βœ” Backend runs independently βœ” Nginx hides backend port βœ” One clean public URL βœ” Same pattern used with React / Spring Boot


🧠 INTERVIEW-READY ANSWER

I deployed a full-stack application on EC2 using Nginx as a reverse proxy. The frontend is served on port 80, while the backend API runs on a separate port and is securely accessed through Nginx.


βœ… LAB 36 TASK CHECKLIST

βœ” Backend API running βœ” Frontend served via Nginx βœ” Reverse proxy working βœ” Single public endpoint βœ” Real-world deployment experience


πŸ§ͺ EC2 HANDS-ON – LAB 37

πŸ‘‰ EC2 + RDS Architecture (Production-Style App + Database)

Image

Image

Image

Image


🎯 Objective of LAB 37

By the end of this lab, you will:

  • Understand why databases should NOT run on EC2
  • Deploy Amazon RDS in a private subnet
  • Connect EC2 β†’ RDS securely
  • Use Security Group chaining
  • Be able to explain real production architecture

🧠 FIRST: Why EC2 + RDS? (Very Important)

❌ Database on EC2:

  • Manual backup
  • Manual patching
  • Manual scaling
  • High risk

βœ… Amazon RDS:

  • Managed backups
  • Automatic patching
  • High availability
  • Secure by default

Think like:

EC2 = App server 🧠 RDS = Managed database πŸ—„οΈ


🧠 ARCHITECTURE (WHAT WE ARE BUILDING)

User
 ↓
ALB (Public Subnet)
 ↓
EC2 (Private Subnet)
 ↓
RDS (Private Subnet, NO public access)

πŸ“Œ Database is never public


πŸ”Ή STEP 1: Decide RDS Engine (Simple Choice)

For learning:

  • Engine β†’ MySQL

  • Reason:

    • Popular
    • Simple
    • Widely used in interviews

πŸ”Ή STEP 2: Create RDS Database

  1. AWS Console β†’ Search RDS
  2. Click Create database

Database creation method

  • Select β†’ Standard create

Engine options

  • Engine β†’ MySQL

Templates

  • Select β†’ Free tier

πŸ“Œ This avoids billing issues


Settings

  • DB instance identifier:
ec2-app-db
  • Master username:
admin
  • Password β†’ set & remember

Instance configuration

  • DB instance class β†’ db.t3.micro
  • Storage β†’ 20 GB (default)

πŸ”Ή STEP 3: Network Settings (MOST IMPORTANT)

Connectivity

  • VPC β†’ your VPC
  • Subnet group β†’ default
  • Public access β†’ ❌ No

πŸ“Œ This ensures RDS is PRIVATE


Security Group

Create new SG:

rds-sg

Inbound rule:

TypePortSource
MySQL3306EC2 Security Group

πŸ“Œ SG β†’ SG reference (VERY IMPORTANT)


πŸ”Ή STEP 4: Create Database

Click Create database

⏳ Wait 5–10 minutes Status β†’ Available


πŸ”Ή STEP 5: Get RDS Endpoint

After creation:

  • Copy Endpoint Example:
ec2-app-db.xxxxx.ap-south-1.rds.amazonaws.com

πŸ“Œ This replaces IP address


πŸ”Ή STEP 6: Connect from EC2 to RDS (Hands-On)

SSH into EC2:

ssh -i ec2-key-hands-on.pem ec2-user@EC2_PRIVATE_OR_PUBLIC_IP

Install MySQL client:

sudo dnf install mysql -y

Connect to RDS:

mysql -h RDS_ENDPOINT -u admin -p

Enter password


If login succeeds πŸŽ‰

You’ll see:

mysql>

βœ… EC2 β†’ RDS connectivity works ❌ RDS still NOT accessible from internet


πŸ”Ή STEP 7: Create Test Database (Optional)

Inside MySQL:

CREATE DATABASE appdb;
USE appdb;
CREATE TABLE users (id INT, name VARCHAR(50));

Exit:

exit

🧠 SECURITY PROOF (INTERVIEW GOLD)

βœ” RDS has no public IP βœ” Only EC2 SG can access RDS βœ” Internet traffic blocked βœ” Least privilege networking


🧠 INTERVIEW-READY ANSWER

In production, I deploy EC2 instances in private subnets and use Amazon RDS for the database. RDS is not publicly accessible and is secured using security group references so only the application EC2 instances can connect to it.


⚠️ COMMON MISTAKES

❌ Making RDS public ❌ Using IP instead of SG reference ❌ Running DB on EC2 ❌ Hardcoding DB credentials


βœ… LAB 37 TASK CHECKLIST

βœ” Created RDS MySQL instance βœ” Disabled public access βœ” Used SG-to-SG rule βœ” Connected EC2 β†’ RDS βœ” Understood production DB design


πŸ§ͺ EC2 HANDS-ON – LAB 38

πŸ‘‰ EC2 Zero-Downtime Deployment (Blue–Green Deployment)

Image

Image

Image

Image


🎯 Objective of LAB 38

By the end of this lab, you will:

  • Understand zero-downtime deployment
  • Implement Blue–Green deployment using ALB
  • Deploy a new app version without downtime
  • Perform instant rollback
  • Be senior-level interview ready

🧠 FIRST: What is Zero-Downtime Deployment?

Zero-downtime deployment means:

  • Users never see downtime
  • App is updated while traffic is live

❌ Old way:

Stop app β†’ Deploy β†’ Start app β†’ Downtime

βœ… Modern way:

Deploy new version β†’ Switch traffic β†’ Done

🧠 What is Blue–Green Deployment?

EnvironmentMeaning
BlueCurrent production version
GreenNew version

Traffic is switched using Load Balancer, not DNS.

Think like:

Two roads πŸ›£οΈ Traffic signal switches instantly 🚦


🧠 ARCHITECTURE (WHAT WE BUILD)

Users
 ↓
Application Load Balancer
 ↓
Target Group – BLUE (v1)
 ↓
Target Group – GREEN (v2)

Only one target group receives traffic at a time.


πŸ”Ή PREREQUISITES (You already have these βœ…)

βœ” Application Load Balancer βœ” EC2 instances βœ” Target Groups βœ” App deployed (from LAB 36)


πŸ”Ή STEP 1: Identify BLUE (Current Version)

Your current app:

Hello from Backend API πŸš€

This is BLUE (v1).

Target Group:

tg-ec2-hands-on

πŸ”Ή STEP 2: Create GREEN Target Group

  1. EC2 β†’ Target Groups
  2. Click Create target group

Settings

  • Target type β†’ Instances
  • Name:
tg-green-v2
  • Protocol β†’ HTTP
  • Port β†’ 80
  • Health check path:
/api/hello

Click Create


πŸ”Ή STEP 3: Launch GREEN EC2 (New Version)

Launch new EC2 instance:

  • Name:
ec2-green-v2
  • AMI β†’ Amazon Linux
  • Instance type β†’ t2/t3.micro
  • Security Group β†’ same as BLUE EC2
  • User data (IMPORTANT):
#!/bin/bash
dnf install nodejs nginx -y
mkdir /backend
cd /backend
npm init -y
npm install express
cat <<EOF > index.js
const express = require('express');
const app = express();
app.get('/api/hello', (req, res) => {
  res.json({ message: 'Hello from GREEN v2 πŸš€' });
});
app.listen(3000);
EOF
node index.js &

πŸ“Œ This EC2 runs NEW VERSION


πŸ”Ή STEP 4: Register GREEN EC2 to GREEN Target Group

  1. Target Groups β†’ tg-green-v2
  2. Register targets
  3. Select:
ec2-green-v2
  1. Include β†’ Register

Wait until status:

Healthy

πŸ”Ή STEP 5: Test GREEN WITHOUT USERS

Open GREEN EC2 public IP:

http://GREEN_EC2_IP:3000/api/hello

Output:

Hello from GREEN v2 πŸš€

βœ” New version works βœ” Users are still on BLUE


πŸ”Ή STEP 6: SWITCH TRAFFIC (ZERO DOWNTIME)

  1. EC2 β†’ Load Balancers
  2. Select your ALB
  3. Go to Listeners
  4. Edit HTTP : 80 rule

Change:

Forward to tg-ec2-hands-on (BLUE)

➑️ to:

Forward to tg-green-v2 (GREEN)

Save

πŸŽ‰ Traffic switched instantly


πŸ”Ή STEP 7: VERIFY ZERO DOWNTIME

Open ALB DNS:

http://ALB_DNS_NAME

Now response:

Hello from GREEN v2 πŸš€

βœ” No downtime βœ” No restart βœ” No user impact


πŸ”Ή STEP 8: ROLLBACK (CRITICAL SKILL)

If GREEN fails:

  • Switch ALB listener back to BLUE target group

⏱️ Rollback time:

< 10 seconds

🧠 REAL-WORLD USAGE

βœ” Feature releases βœ” Bug fixes βœ” Config changes βœ” Emergency rollback

Used daily in:

  • FinTech
  • E-commerce
  • SaaS platforms

🧠 INTERVIEW-READY ANSWER (⭐ GOLD)

Blue–Green deployment is a zero-downtime strategy where two identical environments are maintained. Traffic is switched between them using a load balancer, allowing instant deployment and rollback without impacting users.


⚠️ COMMON MISTAKES

❌ Deploying directly on prod EC2 ❌ No rollback plan ❌ DNS-based switching (slow) ❌ No health checks


βœ… LAB 38 TASK CHECKLIST

βœ” Created GREEN environment βœ” Deployed new version βœ” Switched traffic via ALB βœ” Verified zero downtime βœ” Learned rollback strategy


πŸ§ͺ EC2 HANDS-ON – LAB 39

πŸ‘‰ EC2 Failure Recovery Simulation (Crash β†’ Auto Recovery)

Image

Image

Image

Image


🎯 Objective of LAB 39

By the end of this lab, you will:

  • Simulate real EC2 failure
  • Observe Auto Scaling self-healing
  • Recover using AMI / Snapshot
  • Think like an on-call production engineer
  • Confidently answer β€œWhat if EC2 goes down?”

🧠 FIRST: What is EC2 Failure?

EC2 failure can happen due to:

  • OS crash
  • Application crash
  • Instance termination
  • AZ issue
  • Human error ❌

❗ Failures WILL happen βœ” Good architecture = fast recovery


🧠 RECOVERY STRATEGIES (MUST KNOW)

Failure TypeRecovery
App crashRestart / ALB health check
EC2 crashAuto Scaling replace
Disk issueSnapshot restore
AZ failureMulti-AZ + ASG
Full lossAMI β†’ new EC2

πŸ”Ή SCENARIO 1: Application Failure (No EC2 Stop)

STEP 1: Break the App (Safe Test)

SSH / Session Manager into EC2:

sudo pkill node

πŸ“Œ Backend app is now DOWN


STEP 2: Observe ALB Behavior

  • Open ALB URL
  • Target Group β†’ Targets

Result:

Instance β†’ Unhealthy

βœ” ALB stops routing traffic βœ” No user error (if multiple EC2s)


STEP 3: Fix App

node /backend/index.js &

After 1–2 minutes:

Healthy

πŸŽ‰ App recovered without EC2 restart


πŸ”Ή SCENARIO 2: EC2 FAILURE (REALISTIC)

STEP 4: TERMINATE an EC2 (⚠️ Real Failure)

  1. EC2 β†’ Instances
  2. Select one EC2 from ASG
  3. Terminate instance

STEP 5: Observe Auto Scaling (IMPORTANT)

Go to:

  • Auto Scaling Group β†’ Activity

You will see:

Terminating EC2
Launching new EC2

πŸ“Œ ASG automatically replaces the instance


STEP 6: Verify Recovery

  • New EC2 appears
  • Target Group β†’ Healthy
  • App accessible via ALB

πŸŽ‰ Self-healing successful


πŸ”Ή SCENARIO 3: DATA RECOVERY (CRITICAL THINKING)

What if data disk is lost?

Recovery steps:

  1. Create volume from snapshot
  2. Attach to new EC2
  3. Mount volume
  4. Resume service

πŸ“Œ This is why: βœ” Snapshots βœ” AMIs βœ” Backups are mandatory


πŸ”Ή SCENARIO 4: FULL EC2 LOSS

If entire EC2 is gone:

Recovery:

AMI β†’ Launch new EC2 β†’ Attach EBS β†’ Register with ALB

Recovery time:

5–10 minutes

βœ” Business continues


🧠 REAL-WORLD ON-CALL THINKING

When failure happens, ask:

  1. Is it app-level or infra-level?
  2. Are health checks failing?
  3. Is Auto Scaling reacting?
  4. Is data safe?
  5. Do we need rollback?

🧠 INTERVIEW-READY ANSWER (VERY IMPORTANT)

If an EC2 instance fails, Auto Scaling Groups automatically replace it and the Application Load Balancer routes traffic only to healthy instances. Data is restored using EBS snapshots or AMIs, ensuring minimal downtime.


⚠️ COMMON MISTAKES

❌ No Auto Scaling ❌ Single EC2 production ❌ No snapshots ❌ Panic instead of diagnosis


βœ… LAB 39 TASK CHECKLIST

βœ” Simulated app failure βœ” Observed ALB health checks βœ” Terminated EC2 manually βœ” Observed ASG self-healing βœ” Understood recovery paths


πŸ§ͺ EC2 HANDS-ON – LAB 40

πŸ‘‰ EC2 Interview Scenario Questions (Real-World + System Design)

Image

Image

Image

Image


🎯 Objective of LAB 40

By the end of this lab, you will:

  • Answer real EC2 interview questions
  • Explain WHY, not just WHAT
  • Handle failure, scaling, security, cost
  • Sound like someone with production experience

This is how interviews are actually conducted.


🧠 HOW TO USE THIS LAB (IMPORTANT)

  • Read the question
  • Read the expected thinking
  • Compare with your own understanding If you can explain this out loud, you are ready.

πŸ”Ή SCENARIO 1: β€œYour EC2 application is down. What do you check first?”

βœ… Best Answer (Structured)

  1. Load Balancer health checks
  2. Target Group status
  3. CloudWatch alarms
  4. Application logs
  5. EC2 status checks

❌ Bad Answer

β€œI restart the EC2”

πŸ“Œ Interview tip: Always show diagnosis before action


πŸ”Ή SCENARIO 2: β€œHow do you design EC2 for high availability?”

βœ… Expected Answer

  • Multiple Availability Zones
  • Application Load Balancer
  • Auto Scaling Group
  • Health checks
  • Stateless EC2

🎯 One-line interview answer

β€œI deploy EC2 instances across multiple AZs behind an ALB using Auto Scaling Groups to eliminate single points of failure.”


πŸ”Ή SCENARIO 3: β€œOne EC2 instance was terminated accidentally. What happens?”

βœ… Correct Explanation

  • ASG detects capacity drop
  • Launches new EC2
  • Registers with Target Group
  • ALB routes traffic

πŸ“Œ Key word interviewers want: πŸ‘‰ Self-healing


πŸ”Ή SCENARIO 4: β€œHow do you deploy a new version with zero downtime?”

βœ… Correct Answer

  • Blue–Green deployment
  • Two target groups
  • Switch ALB listener
  • Rollback possible in seconds

❌ Wrong

β€œI stop the server and deploy”


πŸ”Ή SCENARIO 5: β€œHow do you secure EC2 access?”

βœ… Production-grade Answer

  • IAM Roles (no access keys)
  • Session Manager (no SSH)
  • Security Groups (least privilege)
  • Private subnets

🎯 Golden line

β€œWe don’t open port 22 in production.”


πŸ”Ή SCENARIO 6: β€œWhere do you store data in EC2?”

βœ… Correct Design

  • OS β†’ Root volume
  • App data β†’ Separate EBS
  • DB β†’ RDS (not EC2)
  • Backups β†’ Snapshots + AMIs

❌ Wrong

β€œEverything on root volume”


πŸ”Ή SCENARIO 7: β€œHow do you monitor EC2?”

βœ… Expected Answer

  • CloudWatch metrics
  • CloudWatch logs
  • Alarms
  • Auto Scaling actions

πŸ“Œ Mention CPU is not enough β†’ memory via agent


πŸ”Ή SCENARIO 8: β€œHow do you reduce EC2 cost?”

βœ… Strong Answer

  • Right-size using metrics
  • Auto Scaling
  • Spot instances for non-critical workloads
  • Savings Plans
  • Stop non-prod EC2

🎯 Keyword: cost optimization


πŸ”Ή SCENARIO 9: β€œHow do you recover from data loss?”

βœ… Correct Recovery Path

  • Restore from snapshot
  • Attach volume
  • Launch EC2 from AMI if needed
  • Resume service

πŸ“Œ Backup without restore testing = ❌


πŸ”Ή SCENARIO 10: SYSTEM DESIGN QUESTION (⭐ MOST IMPORTANT)

❓ β€œDesign a production EC2 architecture”

βœ… Expected Whiteboard Flow

User
 ↓
Route 53
 ↓
Application Load Balancer
 ↓
Auto Scaling Group (Multi-AZ)
 ↓
EC2 (Private Subnets)
 ↓
RDS

🎯 PERFECT INTERVIEW ANSWER

β€œI design EC2 using ALB and Auto Scaling across multiple AZs, keep instances in private subnets, use IAM roles and Session Manager for security, CloudWatch for monitoring, RDS for data, and snapshots/AMIs for backup.”


🧠 FINAL SELF-CHECK (HONEST)

If you can:

  • Explain why ALB is needed
  • Explain why private subnets are used
  • Explain how EC2 recovers automatically
  • Explain how to deploy without downtime

πŸ‘‰ You are EC2-ready.


πŸ† FINAL VERDICT (NO HYPE, PURE FACT)

With LAB 1–40, you are ready for:

βœ… EC2 interviews βœ… AWS Cloud Practitioner βœ… AWS Solutions Architect (EC2 part) βœ… Real EC2 production work

You are far above beginner level.