DEV Community

Aisalkyn Aidarova
Aisalkyn Aidarova

Posted on

AWS introduction

๐Ÿงพ AWS Billing, Budget, and Cost Management โ€“ Step-by-Step

1. Access the Billing Console

  • In the AWS Management Console, click your account name (top right).
  • Choose Billing and Cost Management.

โš ๏ธ If you see โ€œAccess Deniedโ€ โ€” you are using an IAM user.
Only the root account can enable billing access for IAM users.


2. Enable Billing Access for IAM Users

  • Sign in as the root account owner.
  • Go to Account โ†’ IAM user and role access to billing information.
  • Turn ON โ€œActivate IAM access.โ€

Now IAM users with admin permissions can view billing.


3. View Billing Data

  • Go back to Billing โ†’ Bills.
  • You can now see:

    • Month-to-date costs
    • Forecasted cost
    • Charges by service (e.g., EC2, S3, etc.)
  • Click on a month โ†’ scroll to Charges by Service to identify what costs money (e.g., NAT Gateway, EBS, etc.).


4. Check the Free Tier

  • Go to Billing โ†’ Free Tier.
  • Shows:

    • Usage vs Free Tier limit
    • Forecasted overages
  • If usage turns red, youโ€™re about to be charged โ€” stop or delete resources.


5. Create a Budget

  • Go to Billing โ†’ Budgets โ†’ Create budget.
  • Choose โ€œUse a template (simplified)โ€.

Option A: Zero Spend Budget

  • Template: Zero spend
  • Name: My Zero Spend Budget
  • Alert email: your address (e.g., yourname@example.com)
  • Sends alert as soon as you spend $0.01.

Option B: Monthly Cost Budget

  • Template: Monthly cost budget
  • Limit: e.g., $10
  • Add alert recipients.
  • Alerts at:

    • 85% of actual spend
    • 100% of actual spend
    • 100% of forecasted spend

โœ… Result

Youโ€™ll get an email warning if:

  • You spend 1 cent (zero spend budget), or
  • Your forecasted/actual spend hits your limit.

This ensures students donโ€™t overspend during AWS labs.

โ˜๏ธ Amazon EC2 โ€“ Elastic Compute Cloud

1. What is EC2?

  • EC2 = Elastic Compute Cloud
  • Itโ€™s AWSโ€™s main Infrastructure as a Service (IaaS) offering.
  • Lets you rent virtual machines (VMs) โ€” called EC2 Instances โ€” on demand.
  • Foundation of AWS: most AWS services depend on EC2 behind the scenes.

2. Key EC2 Components

Component Description
EC2 Instance The virtual server you rent from AWS.
EBS Volume Elastic Block Storage โ€“ a network-attached disk for your instance.
Elastic Load Balancer (ELB) Distributes incoming traffic across multiple instances.
Auto Scaling Group (ASG) Automatically increases or decreases the number of running instances based on demand.
Security Group Acts as a firewall โ€” controls inbound/outbound traffic to the instance.
Elastic IP A static public IP address you can attach to your instance.
User Data Script that runs once when the instance boots โ€” used for automation/setup tasks.

3. Choosing EC2 Instance Settings

When launching an EC2 instance, you choose:

Option Examples / Details
Operating System Linux (most popular), Windows, or macOS.
Compute (vCPUs) Choose instance type (e.g., t2.micro, t3.medium) based on performance.
Memory (RAM) Depends on workload size (web server vs. database).
Storage - EBS: network-attached, persistent storage.
- Instance Store: local hardware disk (temporary).
Network Select subnet, VPC, and network interface (speed, public IP, etc.).
Firewall Rules Configure Security Groups โ€” open only necessary ports (e.g., 22 for SSH, 80 for HTTP).

4. Bootstrapping with User Data

Bootstrapping = running setup commands automatically when the instance launches.

โœ… Common tasks in User Data:

  • Update packages (yum update -y or apt update -y)
  • Install software (e.g., Nginx, Apache, Python)
  • Download configuration files
  • Start services automatically

๐Ÿง  Notes:

  • Runs only once at first boot.
  • Executed as root user (no need for sudo).
  • Makes EC2 setup automated and repeatable.

Example:

#!/bin/bash
yum update -y
yum install -y nginx
systemctl start nginx
systemctl enable nginx
echo "<h1>Hello from EC2</h1>" > /usr/share/nginx/html/index.html
Enter fullscreen mode Exit fullscreen mode

5. Why EC2 Matters

  • Core building block of the AWS ecosystem.
  • Lets you quickly deploy servers on demand.
  • Forms the base for many other services (ECS, EKS, Beanstalk, etc.).
  • Teaches the foundation of cloud computing: scalability, pay-as-you-go, and automation.

๐Ÿš€ Launching Your First EC2 Instance (Amazon Linux)

1. What Youโ€™ll Do

You will:

  • Launch your first EC2 instance (a virtual server).
  • Use User Data to automatically install a web server.
  • Access the website through a browser.
  • Learn to start, stop, and terminate the instance.

2. Launch an Instance

Step 1: Open EC2 Console

  • Go to AWS Management Console โ†’ EC2 โ†’ Instances
  • Click Launch Instances

Step 2: Name and Tags

  • Name: My First Instance
  • (Tag Key = Name, Value = My First Instance)

Step 3: Choose an AMI (Amazon Machine Image)

  • Go to Quick Start โ†’ Amazon Linux 2 AMI (64-bit x86)
  • โœ… Free Tier eligible

This defines the operating system for your EC2 instance.


Step 4: Choose Instance Type

  • Choose t2.micro (Free Tier eligible)
  • 1 vCPU, 1 GB RAM
  • Perfect for small practice servers

Step 5: Create or Choose Key Pair

Youโ€™ll need a key to connect via SSH later.

  • Name: EC2Tutorial
  • Type: RSA
  • Format:

    • .pem โ†’ for Mac, Linux, or Windows 10+
    • .ppk โ†’ for older Windows (PuTTY)
  • Download and save it safely โ€” AWS will not let you download again!


Step 6: Configure Network Settings

  • Leave defaults (public IP assigned automatically).
  • Create a Security Group (default name: launch-wizard-1).
  • Add inbound rules:

    • SSH (port 22) โ†’ Source: Anywhere
    • HTTP (port 80) โ†’ Source: Anywhere (This allows browser access.)

Step 7: Configure Storage

  • Default: 8 GB gp2 EBS volume
  • You get up to 30 GB free under Free Tier.
  • Option โ€œDelete on Terminationโ€ = Yes (keeps cleanup simple).

Step 8: Add User Data Script

Scroll to Advanced details โ†’ User data
Paste this script:

#!/bin/bash
yum update -y
yum install -y httpd
systemctl start httpd
systemctl enable httpd
echo "<h1>Hello World from $(hostname -f)</h1>" > /var/www/html/index.html
Enter fullscreen mode Exit fullscreen mode

This will:

  • Update the system
  • Install Apache web server
  • Enable it at boot
  • Create a simple โ€œHello Worldโ€ web page

Step 9: Launch

  • Review โ†’ Launch instance
  • Go to View all instances
  • Wait until Instance State = running (takes ~10โ€“15 seconds)

3. Access the Website

  • Copy your Public IPv4 address
  • In your browser, enter:
  http://<Public-IP>
Enter fullscreen mode Exit fullscreen mode
  • (โš ๏ธ Use http, not https.)
  • Youโ€™ll see: Hello World from 172.x.x.x โ€” where the number is the private IP.

4. Manage the Instance

Action What It Does Note
Stop Instance Shuts down the server Youโ€™re not billed while stopped
Start Instance Restarts it later โš ๏ธ May get a new public IP
Terminate Instance Deletes server + volume Irreversible โ€” removes data

๐Ÿง  The private IP stays the same, but the public IP changes after every stop/start cycle unless you assign an Elastic IP.


5. Key Takeaways

  • You can launch a web server in minutes without owning hardware.
  • User Data automates setup during boot.
  • Learn to stop/terminate to avoid charges.
  • EC2 is the core of cloud computing โ€” flexible, fast, pay-as-you-go.

โš™๏ธ Amazon EC2 Instance Types

1. Why EC2 Instance Types Exist

AWS offers different EC2 instance types to match different workloads โ€”
from lightweight web servers to machine learning and databases.

Each type has:

  • Different CPU, RAM, and network capabilities
  • Different optimization (compute, memory, storage, or networking)
  • Different pricing

2. EC2 Instance Naming Convention

Example: m5.2xlarge

Part Meaning Example
m Instance class / family m = general purpose
5 Generation 5 = newer than 4, older than 6
2xlarge Size Larger = more vCPUs & memory

So m5.2xlarge means:
โžก๏ธ General-purpose instance, generation 5, with 2xlarge size (moderate CPU and memory).


3. EC2 Instance Families (Main Categories)

Type Family Prefix Description Example Use Cases
๐Ÿงฉ General Purpose t, m, a Balanced CPU, memory, and networking Web servers, code repos, dev/test environments
โšก Compute Optimized c High CPU performance Batch processing, media encoding, gaming, ML inference
๐Ÿง  Memory Optimized r, x, z High RAM for in-memory processing Databases, caching (Redis), analytics, BI
๐Ÿ’พ Storage Optimized i, d, h High local disk throughput Big data, OLTP, NoSQL, data warehousing
๐ŸŽฎ Accelerated Computing p, g, f GPUs or FPGAs AI/ML training, deep learning, rendering, HPC

4. Common Instance Examples

Instance vCPU Memory (GB) Optimized For
t2.micro 1 1 General-purpose, free tier
m5.large 2 8 Balanced web/app server
c5.4xlarge 16 32 Compute-intensive tasks
r5.16xlarge 64 512 Memory-heavy databases
i3.8xlarge 32 244 Storage-optimized, high IOPS

5. Helpful Reference Websites

๐Ÿ”— AWS Official Instance Types Page

https://aws.amazon.com/ec2/instance-types
โ†’ Lists all current instance families, pricing, and features.

๐Ÿ”— EC2Instances.info

https://ec2instances.info
โ†’ Excellent for:

  • Comparing CPU, memory, storage, and cost
  • Searching & filtering instance families
  • Quickly checking On-Demand and Reserved pricing

6. Key Takeaways

โœ… Understand the prefixes:

  • t โ†’ test & dev (burstable)
  • m โ†’ general-purpose
  • c โ†’ compute-heavy
  • r โ†’ memory-heavy
  • i โ†’ storage-heavy
  • p/g โ†’ GPU-based

โœ… Choose instance type by workload:

  • Web apps โ†’ t2.micro, m5.large
  • Databases โ†’ r5.xlarge
  • Machine learning โ†’ p3, g4
  • Data warehousing โ†’ i3, d2

โœ… Use the AWS Free Tier:

  • t2.micro or t3.micro = Free for 12 months (750 hours/month)

๐Ÿ”’ Security Groups in Amazon EC2 (Firewalls)

1. What Are Security Groups?

  • Security Groups (SGs) are virtual firewalls that control traffic into and out of your EC2 instances.
  • They define network access rules based on:

    • Ports (e.g., 22 for SSH, 80 for HTTP)
    • Protocols (TCP, UDP, etc.)
    • Source/Destination (IP ranges or other security groups)

๐Ÿง  Think of a security group as a โ€œprotective shieldโ€ that decides who can talk to your server and on which ports.


2. Basic Behavior

Direction Default Behavior Purpose
Inbound โŒ All traffic blocked by default Protects the instance from unwanted access
Outbound โœ… All traffic allowed by default Lets the instance connect to the internet (updates, downloads, etc.)
  • SGs contain only ALLOW rules (no explicit โ€œdenyโ€).
  • If traffic is not explicitly allowed โ†’ itโ€™s implicitly denied.

3. How Security Groups Work

Example:

You (your computer) are on the public internet, trying to connect to an EC2 instance.

  • The EC2 instance has a Security Group attached.
  • That SG checks its inbound rules:

    • If your IP and port (e.g., 22 or 80) match โ†’ traffic allowed
    • If not โ†’ traffic blocked

Two traffic directions:

  • Inbound rules โ†’ from the outside โ†’ into EC2
  • Outbound rules โ†’ from EC2 โ†’ out to the internet

4. Security Group Rules Format

Field Description Example
Type What kind of connection SSH, HTTP, HTTPS
Protocol Usually TCP TCP
Port Range Communication port 22, 80, 443
Source/Destination IP or Security Group 0.0.0.0/0 (all) or your IP

Example Rule:

Type Protocol Port Source
SSH TCP 22 Your IP (203.x.x.x/32)
HTTP TCP 80 0.0.0.0/0

5. Key Characteristics

โœ… You can attach:

  • One SG โ†’ multiple instances
  • One instance โ†’ multiple SGs

โœ… SGs are:

  • Region-specific
  • VPC-specific

โœ… SGs live outside the instance (so blocked traffic never reaches it).

โœ… If your app times out, itโ€™s probably an SG issue.
If you get connection refused, SG worked but the app isnโ€™t running.


6. Best Practices

  • Create a dedicated SG for SSH (port 22) and restrict it to your IP only. Example: MySSH-SG โ†’ Inbound rule: SSH (22) โ†’ Source: your IP.
  • Create separate SGs for each application/service (e.g., web, database).
  • Regularly review inbound rules โ€” remove unused ones.

7. Referencing Other Security Groups

Security groups can reference other security groups instead of IPs.

Why use it?

When instances must communicate internally (e.g., web server โ†’ database),
you donโ€™t have to manage IP addresses.

Example:

  • SG-Web โ†’ allows inbound HTTP (80) from 0.0.0.0/0
  • SG-DB โ†’ allows inbound MySQL (3306) from SG-Web

โžก๏ธ Any instance with SG-Web can talk to instances with SG-DB over port 3306.

This is common with load balancers and multi-tier apps.


8. Common Ports to Remember

Port Protocol Purpose
22 SSH Linux remote login
21 FTP File Transfer Protocol
22 SFTP Secure File Transfer (uses SSH)
80 HTTP Unsecured web traffic
443 HTTPS Secured web traffic
3389 RDP Remote Desktop (Windows)

9. Quick Recap

โœ… Inbound = Blocked by default
โœ… Outbound = Allowed by default
โœ… Security Groups = ALLOW rules only
โœ… Region + VPC bound
โœ… Timeout โ†’ SG issue, Connection Refused โ†’ App issue


๐Ÿ” Hands-On: Working with Security Groups in EC2


1. Where to Find Security Groups

  • In the EC2 Console, select your instance โ†’ click Security tab.
  • Youโ€™ll see:

    • Inbound rules
    • Outbound rules
    • Linked Security Group(s)

For a full view:
๐Ÿ‘‰ Left menu โ†’ Network & Security โ†’ Security Groups


2. Default Security Groups

Youโ€™ll typically see:

  1. Default security group (created automatically per VPC)
  2. Launch-wizard-1 (created during your first EC2 launch)

Each SG has:

  • A unique ID (e.g., sg-0a12b3c4d5e6f)
  • Inbound rules โ†’ traffic into your instance
  • Outbound rules โ†’ traffic out of your instance

3. Viewing and Editing Inbound Rules

Example: Launch-wizard-1

Type Protocol Port Source Purpose
SSH TCP 22 0.0.0.0/0 Remote terminal access
HTTP TCP 80 0.0.0.0/0 Web server access
  • These rules allowed us to:

    • SSH into the instance (port 22)
    • Access the web page (http://<Public-IP>) on port 80

4. Testing Firewall Behavior

๐Ÿ”ธ Case 1 โ€“ Remove the HTTP rule

  • Delete the inbound rule for port 80.
  • Save changes.
  • Try reloading your website โ†’ โŒ Timeout

๐Ÿง  Timeout = Security Group issue

  • Your request never reached the EC2 instance.
  • Fix: check inbound rules.

๐Ÿ”ธ Case 2 โ€“ Add the HTTP rule back

  • Add inbound rule:

    • Type: HTTP
    • Port: 80
    • Source: Anywhere (0.0.0.0/0)
  • Save rules โ†’ โœ… Refresh your page โ†’ Works again!

The port 80 rule allows public HTTP access to your web server.


5. Adding New Rules

You can:

  • Choose any port or port range (e.g., 443 for HTTPS).
  • Pick from the dropdown list (common protocols).
  • Specify source:

    • Anywhere (0.0.0.0/0) โ†’ open to everyone
    • My IP โ†’ restrict access to your own machine
    • Custom CIDR, security group, or prefix list โ†’ for advanced setups

โš ๏ธ Note: If your IP changes (e.g., new Wi-Fi or VPN), youโ€™ll lose access if rule is โ€œMy IPโ€.


6. Outbound Rules

Default outbound rule:

Type Protocol Port Destination
All traffic All All 0.0.0.0/0

โ†’ This allows your instance to download updates, connect to APIs, or reach the internet freely.


7. Multiple Security Groups and Instances

  • One EC2 instance can have multiple SGs attached.
  • One SG can be attached to multiple EC2 instances.
  • Combined rules are additive โ€” all allowed traffic from each SG is permitted.

8. Quick Diagnostic Tip

Symptom Meaning Fix
โŒ Timeout Blocked by SG (no inbound rule) Add correct inbound rule
โš ๏ธ Connection Refused App/service not running on port Start service inside EC2

โœ… Summary

  • SGs control inbound and outbound traffic.
  • Theyโ€™re stateful โ€” return traffic is automatically allowed.
  • Timeouts = SG misconfiguration, not instance failure.
  • Use least privilege โ†’ only open required ports.
  • One SG = many instances; one instance = many SGs.

๐Ÿงฉ Connecting to Your EC2 Instance


1. Why We Need It

After launching an EC2 instance, the next step is to connect inside the server โ€”
to install software, check logs, or perform maintenance.

To do this securely, AWS provides several connection methods, depending on your computerโ€™s operating system.


2. The SSH Protocol

๐Ÿ” What is SSH?

SSH (Secure Shell) is a protocol that allows secure, encrypted remote access to Linux servers.

It lets you:

  • Run commands directly on your EC2 instance.
  • Manage software, configurations, and troubleshooting.
  • Transfer files securely (via SFTP or SCP).

3. Methods by Operating System

Platform Recommended Method Tool Notes
Mac / Linux SSH command-line Built-in terminal Use ssh -i your-key.pem ec2-user@<Public-IP>
Windows 10 / 11 SSH (built-in PowerShell) Use ssh command Works the same as on Mac/Linux
Windows 7 / 8 (or older) PuTTY Separate application Convert .pem โ†’ .ppk file first
Any OS (browser-based) EC2 Instance Connect AWS Console โ†’ โ€œConnectโ€ โ†’ โ€œEC2 Instance Connectโ€ Easiest, no software setup

4. ๐Ÿง  EC2 Instance Connect (Recommended for Beginners)

โœ… Advantages:

  • Works on Mac, Linux, Windows โ€” any browser.
  • No setup, no key conversion, no CLI required.
  • Uses your AWS credentials securely.
  • Best for quick testing and short sessions.

โš ๏ธ Limitation:

  • Currently supports Amazon Linux 2 and Ubuntu instances only.
  • Not ideal for automation or long-term maintenance.

5. โš™๏ธ When to Use SSH

  • For advanced work, scripting, or automation.
  • When using custom Linux distributions.
  • When setting up multiple servers with consistent access.

Example SSH Command (Mac/Linux/Win10+)

ssh -i ~/Downloads/ec2tutorial.pem ec2-user@<Public-IP>
Enter fullscreen mode Exit fullscreen mode

Replace <Public-IP> with your instanceโ€™s address.
Ensure port 22 is open in your Security Group.


6. Common SSH Connection Issues

Problem Likely Cause Fix
โŒ Timeout Security Group missing port 22 rule Add inbound rule for SSH (port 22, your IP)
โš ๏ธ Permission denied (publickey) Wrong key or wrong user name Use correct .pem and correct user (ec2-user for Amazon Linux)
โ›”๏ธ Connection refused Instance not running or booting Wait for โ€œRunningโ€ state
๐ŸŒ Wrong IP Instance stopped/restarted Use new Public IP or attach an Elastic IP

7. ๐Ÿ’ก Instructor Tips

  • Only one method needs to work (SSH or EC2 Instance Connect).
  • Donโ€™t stress if SSH fails โ€” youโ€™ll still progress fine with EC2 Instance Connect.
  • Keep your .pem key safe โ€” AWS doesnโ€™t allow redownloads.
  • Always check Security Group rules before troubleshooting deeper.

8. ๐Ÿงญ Next Steps

  1. Identify your OS.
  2. Use the right connection method:
  • Mac/Linux โ†’ SSH
  • Windows 10+ โ†’ PowerShell SSH
  • Windows 7/8 โ†’ PuTTY
  • Any OS โ†’ EC2 Instance Connect
    1. Connect and explore your EC2 server.

๐Ÿ’ป Connecting to EC2 with SSH (Mac or Linux)


1. ๐ŸŽฏ Goal

Use SSH (Secure Shell) to remotely access your EC2 instance from your local terminal.
Once connected, youโ€™ll be able to:

  • Run Linux commands directly on the EC2 machine
  • Verify network connectivity
  • Manage and troubleshoot your cloud server

2. ๐Ÿงฑ How SSH Works

Diagram:

Your Laptop (SSH Client)
   โ†“ Port 22 (SSH)
Internet
   โ†“
EC2 Instance (Amazon Linux 2)
Security Group โ†’ allows Port 22 inbound
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • SSH uses Port 22 to securely connect to the server.
  • The Security Group must allow inbound access on Port 22.
  • The connection authenticates using your private key (.pem).

3. ๐Ÿงฉ Preparation Steps

  1. Locate your downloaded key file (e.g. EC2Tutorial.pem).
  • Rename it to remove spaces โ†’ โœ… EC2Tutorial.pem

    1. Move it to a safe folder (e.g. ~/aws-course/).
    2. In AWS Console:
  • Go to EC2 โ†’ Instances

  • Copy your Public IPv4 Address

  • Check Security Group โ†’ must allow:

     Type: SSH | Protocol: TCP | Port: 22 | Source: 0.0.0.0/0
    

4. ๐Ÿ–ฅ๏ธ Navigate to the Key File

Open your terminal:

cd ~/aws-course
ls
Enter fullscreen mode Exit fullscreen mode

You should see:

EC2Tutorial.pem
Enter fullscreen mode Exit fullscreen mode

If not:

  • Use pwd to see where you are.
  • Use cd .. to go up a directory until you find your folder.

5. ๐Ÿ”‘ Set Proper Permissions

Your key file must not be publicly viewable:

chmod 400 EC2Tutorial.pem
Enter fullscreen mode Exit fullscreen mode

This means: only you can read the file.


6. ๐ŸŒ Connect via SSH

Run:

ssh -i EC2Tutorial.pem ec2-user@<Public-IP>
Enter fullscreen mode Exit fullscreen mode

Example:

ssh -i EC2Tutorial.pem ec2-user@54.165.90.11
Enter fullscreen mode Exit fullscreen mode
  • -i โ†’ specify your private key file
  • ec2-user โ†’ default username for Amazon Linux 2
  • <Public-IP> โ†’ your EC2โ€™s public IPv4 address

If prompted with:

Are you sure you want to continue connecting (yes/no)?
Enter fullscreen mode Exit fullscreen mode

โ†’ type yes.


7. โœ… Youโ€™re In!

If successful, your prompt changes:

[ec2-user@ip-172-31-45-20 ~]$
Enter fullscreen mode Exit fullscreen mode

Youโ€™re now inside your EC2 instance.


8. ๐Ÿงช Try Basic Commands

whoami         # shows current user (ec2-user)
hostname       # displays machine name
ping google.com
Enter fullscreen mode Exit fullscreen mode

Press Ctrl + C to stop the ping.


9. ๐Ÿšช Exit the SSH Session

To disconnect:

exit
Enter fullscreen mode Exit fullscreen mode

or press Ctrl + D.


10. โš ๏ธ Important Notes

  • If you stop and start your instance โ†’ the Public IP changes. Update your SSH command accordingly.
  • Keep your .pem file secure โ€” you cannot re-download it from AWS.
  • If you see "Permission denied", check:

    • File permissions (chmod 400)
    • Username (ec2-user)
    • Correct IP address
    • Port 22 open in security group

๐Ÿง  Summary

Step Command Purpose
1 chmod 400 EC2Tutorial.pem Secure key permissions
2 ssh -i EC2Tutorial.pem ec2-user@<Public-IP> Connect to instance
3 whoami / ping google.com Test access
4 exit Disconnect safely

๐Ÿ’ป Connecting to EC2 Using SSH on Windows (PuTTY Method)


1. ๐ŸŽฏ Goal

Learn how to connect (SSH) from a Windows computer to an Amazon Linux 2 EC2 instance using PuTTY.

SSH lets you:

  • Control your EC2 instance remotely from Windows.
  • Run commands directly on your cloud server.
  • Troubleshoot or configure your Linux machine securely.

2. ๐ŸŒ How It Works

Your Windows PC (PuTTY)
   โ†“ Port 22 (SSH)
Internet
   โ†“
EC2 Instance (Amazon Linux 2)
Security Group โ†’ allows Port 22 inbound
Enter fullscreen mode Exit fullscreen mode

โœ… SSH (Secure Shell) runs over Port 22
โœ… The EC2 Security Group must allow:

Type: SSH
Protocol: TCP
Port: 22
Source: 0.0.0.0/0
Enter fullscreen mode Exit fullscreen mode

3. ๐Ÿงฉ Prerequisites

  1. You already launched an EC2 instance (Amazon Linux 2).
  2. You downloaded your key pair file (e.g., EC2Tutorial.pem).
  3. You are using Windows 7, 8, or older (PuTTY required).

For Windows 10+, you can use PowerShell SSH instead.


4. ๐Ÿงฐ Install PuTTY Tools

Go to https://www.putty.org/
Download and install:

  • PuTTY (main SSH app)
  • PuTTYgen (key converter tool)

During setup โ†’ click Next โ†’ Install โ†’ Finish โœ…


5. ๐Ÿ”‘ Convert Your .PEM Key to .PPK

PuTTY requires .ppk format for private keys.

Steps:

  1. Open PuTTYgen.
  2. Click Load.
  3. Navigate to your .pem file (e.g., EC2Tutorial.pem).
  • If itโ€™s not visible โ†’ choose All Files (.) at the bottom right.
    1. Select the file โ†’ click Open.
    2. Youโ€™ll see: "Successfully imported foreign key"
    3. Click Save private key โ†’ choose a name like EC2Tutorial.ppk.
    4. When asked about a passphrase โ†’ click Yes (no passphrase needed).
    5. Save it (e.g., on your Desktop).

โœ… You now have both:

EC2Tutorial.pem  (AWS original)
EC2Tutorial.ppk  (PuTTY-compatible)
Enter fullscreen mode Exit fullscreen mode

6. โš™๏ธ Configure PuTTY to Connect

  1. Open PuTTY.

  2. In Host Name (or IP address), enter:

   ec2-user@<Public-IP>
Enter fullscreen mode Exit fullscreen mode

Example:

   ec2-user@54.167.123.45
Enter fullscreen mode Exit fullscreen mode
  1. Port: 22
    Connection type: SSH

  2. In the Category list โ†’ expand SSH โ†’ click Auth.

  3. Under โ€œPrivate key file for authenticationโ€ โ†’ click Browse.

  4. Select your .ppk file (e.g., EC2Tutorial.ppk).

  5. Go back to Session (top of the list).

  6. Under โ€œSaved Sessions,โ€ name it something like:

   EC2-Instance
Enter fullscreen mode Exit fullscreen mode

Then click Save.

โœ… This stores your connection and key configuration.


7. ๐Ÿ”Œ Connect to EC2

  1. Select your saved session (EC2-Instance).
  2. Click Open.
  3. A security alert appears:

โ€œThe serverโ€™s host key is not cached in the registry.โ€
โ†’ Click Yes (to trust it).

  1. Youโ€™ll see:
   login as:
Enter fullscreen mode Exit fullscreen mode

Type:

   ec2-user
Enter fullscreen mode Exit fullscreen mode
  1. โœ… Youโ€™re in your EC2 instance!

8. ๐Ÿงช Test Commands

Inside PuTTY, try:

whoami          # shows current user
hostname        # shows machine name
ping google.com # tests internet connectivity
Enter fullscreen mode Exit fullscreen mode

To stop the ping โ†’ Ctrl + C.


9. ๐Ÿšช Exit and Reconnect

  • To leave the session:
  exit
Enter fullscreen mode Exit fullscreen mode
  • Next time:

    • Open PuTTY
    • Load your saved session (EC2-Instance)
    • Click Open
    • Youโ€™ll be logged in instantly โ€” no need to reconfigure.

10. โš ๏ธ Common Troubleshooting

Problem Likely Cause Fix
โŒ Timeout Missing SSH rule in Security Group Add inbound rule for port 22
โš ๏ธ No auth methods available Didnโ€™t attach the .ppk key Re-add the private key under SSH โ†’ Auth
โ›”๏ธ Permission denied (publickey) Wrong username Use ec2-user (not root)
๐ŸŒ Connection refused Instance not running or wrong IP Start instance and use new Public IP

๐Ÿง  Key Takeaways

  • PuTTY is the SSH tool for Windows 7/8.
  • Always convert .pem โ†’ .ppk using PuTTYgen.
  • Use ec2-user as the default login for Amazon Linux 2.
  • Always check port 22 is open in your Security Group.
  • Save your session โ€” it saves time for future logins.

๐Ÿ’ป Connecting to EC2 Using SSH on Windows 10 (PowerShell)


1. ๐ŸŽฏ Goal

Learn to connect (SSH) from a Windows 10 or later machine directly to your EC2 instance โ€” without PuTTY โ€” using PowerShell or Command Prompt.


2. ๐Ÿ” What Is SSH?

SSH (Secure Shell) lets you:

  • Remotely control your EC2 Linux server through a command line.
  • Run, install, or troubleshoot applications securely.
  • Avoid using any GUI โ€” all actions happen via text commands.

3. ๐ŸŒ How It Works

Your Windows 10 PC (PowerShell SSH)
   โ†“ Port 22 (SSH)
Internet
   โ†“
EC2 Instance (Amazon Linux 2)
Security Group โ†’ allows Port 22 inbound
Enter fullscreen mode Exit fullscreen mode

โœ… Port 22 must be open in the Security Group:

Type: SSH | Protocol: TCP | Port Range: 22 | Source: 0.0.0.0/0
Enter fullscreen mode Exit fullscreen mode

4. ๐Ÿงฉ Check If SSH Is Available

Open PowerShell or Command Prompt and type:

ssh
Enter fullscreen mode Exit fullscreen mode
  • If you see command help (e.g. usage options) โ†’ SSH is installed. โœ…
  • If not โ†’ install the Windows โ€œOpenSSH Clientโ€ feature or use PuTTY (see previous lecture).

5. ๐Ÿ“ Locate Your Key File

Your key file is the .pem file you downloaded from AWS (e.g. EC2Tutorial.pem).

Steps:

  1. Place it somewhere simple โ€” e.g. Desktop or C:\Users\<YourName>\aws-course
  2. In PowerShell:
   cd .\Desktop
   ls
Enter fullscreen mode Exit fullscreen mode

You should see your .pem file listed.


6. โš™๏ธ Connect Using SSH

The command format is:

ssh -i "EC2Tutorial.pem" ec2-user@<Public-IP>
Enter fullscreen mode Exit fullscreen mode

Example:

ssh -i "EC2Tutorial.pem" ec2-user@3.94.152.11
Enter fullscreen mode Exit fullscreen mode

Explanation:

Part Meaning
-i Path to your private key (.pem file)
ec2-user Default Linux username for Amazon Linux 2
@<Public-IP> The public IPv4 address of your EC2 instance

7. โš ๏ธ First-Time Connection

Youโ€™ll see:

The authenticity of host ... can't be established.
Are you sure you want to continue connecting (yes/no)?
Enter fullscreen mode Exit fullscreen mode

โ†’ Type yes
โœ… You are now inside your EC2 instance!


8. ๐Ÿงฐ If You Get Permission Errors

Windows sometimes restricts .pem file permissions, causing:

Permissions for 'EC2Tutorial.pem' are too open.
Enter fullscreen mode Exit fullscreen mode

Fixing Permissions:

  1. Right-click your .pem file โ†’ Properties
  2. Go to Security tab โ†’ Advanced
  3. Make sure:
  • Owner = your Windows user account
  • Click Change if needed โ†’ type your username โ†’ Check Names โ†’ OK

    1. Click Disable inheritance โ†’ select Remove all inherited permissions
    2. Click Add โ†’ Select a principal
  • Type your username โ†’ Check Names โ†’ OK

  • Give yourself Full control

    1. Apply and close all dialogs.

โœ… Now only you (the owner) have access to the key โ€” SSH will work without warnings.


9. ๐Ÿงช Verify Connection

Once connected, try:

whoami          # shows the current user
hostname        # shows the EC2 machine name
ping google.com # tests internet connectivity
Enter fullscreen mode Exit fullscreen mode

Press Ctrl + C to stop the ping.


10. ๐Ÿšช Exit the Session

To disconnect:

exit
Enter fullscreen mode Exit fullscreen mode

or press Ctrl + D.


11. ๐Ÿง  Key Tips

Action Command/Note
Check SSH installed ssh in PowerShell or CMD
Navigate to key location cd .\Desktop
Connect ssh -i EC2Tutorial.pem ec2-user@<Public-IP>
Fix permissions Change file owner + disable inheritance
Exit exit or Ctrl + D
Public IP changes If you stop/start EC2 โ†’ use new IP address

โœ… Summary

  • Windows 10+ has built-in SSH โ€” no need for PuTTY.
  • Use your .pem key from AWS to authenticate.
  • Adjust file permissions if Windows blocks access.
  • Always ensure port 22 is open in your Security Group.

๐ŸŒ Connecting to EC2 Using EC2 Instance Connect (Browser-Based SSH)


1. ๐ŸŽฏ Goal

Learn to connect to your Amazon EC2 instance directly from the AWS Console โ€”
without needing any .pem key, PuTTY, or terminal setup.

This method works on Windows, Mac, and Linux using only a web browser.


2. โš™๏ธ What Is EC2 Instance Connect?

EC2 Instance Connect is a browser-based SSH client built into AWS.

It:

  • Lets you open a secure terminal session in your browser.
  • Uses a temporary SSH key (uploaded automatically by AWS).
  • Requires no manual key management.
  • Works with Amazon Linux 2 and Ubuntu instances.

3. ๐Ÿงฑ How It Works

Browser (AWS Console)
   โ†“ HTTPS (Port 443)
AWS EC2 Instance Connect Service
   โ†“ Temporary SSH key (Port 22)
EC2 Instance (Amazon Linux 2)
Security Group โ†’ must allow inbound port 22
Enter fullscreen mode Exit fullscreen mode

โœ… Behind the scenes, it still uses SSH โ€”
so port 22 must be open in your Security Group.


4. ๐Ÿš€ Step-by-Step: Connecting

  1. Go to EC2 Console โ†’ Instances
  2. Select your instance (e.g. My First Instance)
  3. Click Connect (top right)
  4. Choose EC2 Instance Connect (browser-based SSH)
  5. Confirm details:
  • Instance ID: prefilled
  • Public IPv4 address: visible
  • Username: ec2-user (default for Amazon Linux 2)
    1. Click Connect

โœ… Within seconds, a new browser tab opens โ€” you are now inside your EC2 instance terminal!


5. ๐Ÿงช Try Some Commands

In the browser terminal:

whoami          # shows 'ec2-user'
hostname        # shows internal hostname
ping google.com # test connectivity
Enter fullscreen mode Exit fullscreen mode

Press Ctrl + C to stop the ping.


6. ๐Ÿ”’ Troubleshooting EC2 Instance Connect

โŒ Connection Error:

โ€œThere was a problem connecting to your instanceโ€

โœ… Fix: Ensure Port 22 Is Open

  1. Go to EC2 โ†’ Security Groups
  2. Select the group attached to your instance.
  3. Click Edit inbound rules
  4. Add:
   Type: SSH | Protocol: TCP | Port Range: 22 | Source: 0.0.0.0/0
Enter fullscreen mode Exit fullscreen mode
  1. (Optional) Add IPv6 rule if needed:
   Type: SSH | Protocol: TCP | Port Range: 22 | Source: ::/0
Enter fullscreen mode Exit fullscreen mode
  1. Save changes โ†’ try connecting again.

7. ๐Ÿง  Key Points to Remember

  • EC2 Instance Connect is quickest for beginners โ€” no setup, no key downloads.
  • It still relies on SSH port 22 โ€” inbound rules must allow access.
  • It uses temporary credentials valid only for the session.
  • If you remove the SSH rule โ†’ connection fails immediately.
  • Works best for short admin sessions or training labs.

8. โœ… Summary

Feature EC2 Instance Connect
Setup required None (browser only)
SSH key needed Temporary key handled by AWS
Port required 22 (SSH)
Supported OS Amazon Linux 2, Ubuntu
Security Uses HTTPS + ephemeral SSH key
Best for Quick access, demos, and student labs

๐Ÿ” Using IAM Roles with EC2 Instances


1. ๐ŸŽฏ Goal

Learn how to securely give your EC2 instance permission to access AWS services using IAM Roles โ€”
without storing Access Keys or running aws configure.


2. ๐Ÿ’ก Why IAM Roles?

In AWS, EC2 instances often need to access other services (like S3, DynamoDB, or IAM).
You could use AWS credentials (Access Key + Secret Key) โ€” but thatโ€™s unsafe.

โŒ Bad Practice:

Running:

aws configure
Enter fullscreen mode Exit fullscreen mode

and entering your personal IAM user credentials exposes them to anyone with instance access.
They could retrieve keys and use them elsewhere โ€” a major security risk.

โœ… Correct Practice:

Use an IAM Role attached to the EC2 instance.
AWS automatically injects temporary credentials through the instance metadata service.


3. โš™๏ธ How It Works

EC2 Instance
   โ†•
IAM Role attached
   โ†•
AWS automatically provides temporary credentials
   โ†•
Access to AWS services (like IAM, S3, DynamoDB)
Enter fullscreen mode Exit fullscreen mode

โœ” No keys stored
โœ” Rotates automatically
โœ” Least privilege by policy


4. ๐Ÿงช Hands-On: Attach an IAM Role to EC2

Step 1: Connect to EC2

Use EC2 Instance Connect or SSH โ€” both open a terminal inside your EC2.

In the shell, verify connection:

whoami
ping google.com
Enter fullscreen mode Exit fullscreen mode

Then clear the screen:

clear
Enter fullscreen mode Exit fullscreen mode

Step 2: Test AWS CLI Access

Try:

aws iam list-users
Enter fullscreen mode Exit fullscreen mode

Youโ€™ll see:

Unable to locate credentials. You can configure credentials by running "aws configure".
Enter fullscreen mode Exit fullscreen mode

This confirms your instance currently has no permissions.


Step 3: Create an IAM Role (if not already)

In AWS Console โ†’ IAM โ†’ Roles โ†’ Create role

  1. Trusted entity: AWS Service
  2. Use case: EC2
  3. Attach permissions policy:
  • Choose IAMReadOnlyAccess (for demo)
    1. Name: DemoRoleForEC2
    2. Create role

Step 4: Attach Role to Instance

In AWS Console:

  1. Go to EC2 โ†’ Instances
  2. Select your instance โ†’ Actions โ†’ Security โ†’ Modify IAM Role
  3. From the dropdown, choose DemoRoleForEC2
  4. Click Save

Now go to the Security tab of your instance โ€”
youโ€™ll see:

IAM Role: DemoRoleForEC2
Enter fullscreen mode Exit fullscreen mode

Step 5: Test Again

Back in the terminal:

aws iam list-users
Enter fullscreen mode Exit fullscreen mode

โœ… You now get a proper IAM response:

{
  "Users": [
    {
      "UserName": "AdminUser",
      "Arn": "arn:aws:iam::123456789012:user/AdminUser",
      ...
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

Step 6: Remove and Re-Test

Detach the policy from your IAM role (in IAM console โ†’ Role โ†’ Permissions โ†’ Detach policy).

Then rerun:

aws iam list-users
Enter fullscreen mode Exit fullscreen mode

โŒ Now you get:

An error occurred (AccessDenied) when calling the ListUsers operation: User is not authorized to perform iam:ListUsers
Enter fullscreen mode Exit fullscreen mode

โœ… This proves that permissions are directly controlled by the IAM Role.


5. ๐Ÿ” How the Role Credentials Work

You can check the temporary credentials with:

curl http://169.254.169.254/latest/meta-data/iam/security-credentials/
Enter fullscreen mode Exit fullscreen mode

This returns your IAM role name and a short-lived credential set.
AWS automatically rotates these keys for you.


6. ๐Ÿง  Key Takeaways

Concept Explanation
IAM Role Securely grants permissions to EC2 without credentials
Policy Defines what actions EC2 can perform
AWS CLI Automatically uses temporary role credentials
Never use aws configure Donโ€™t hardcode keys on EC2
IAMReadOnlyAccess Safe policy to view IAM data
Metadata service Provides auto-rotated credentials to EC2

โœ… Summary

  • Never use static IAM keys inside EC2.
  • Always attach an IAM Role to the instance.
  • The role defines what AWS actions the instance can perform.
  • IAM credentials are automatically provided and rotated by AWS.
  • Use aws cli commands directly โ€” no configuration needed.

๐Ÿ’ฐ EC2 Instance Purchasing Options


1. ๐ŸŽฏ Goal

Understand how AWS offers different pricing models for EC2 โ€”
each optimized for cost, flexibility, or stability โ€” depending on workload type.


2. โš™๏ธ Overview

AWS gives you six main purchasing options for EC2 instances:

Type Duration Best For Discount (vs On-Demand) Reliability
On-Demand Pay-as-you-go Short, unpredictable workloads โ€“ โญโญโญโญโญ
Reserved Instances (RI) 1 or 3 years Predictable, long-term workloads Up to 72% โญโญโญโญโญ
Savings Plans 1 or 3 years Long-term spend commitment (flexible usage) Up to 72% โญโญโญโญโญ
Spot Instances Variable Short, flexible, fault-tolerant tasks Up to 90% โญโญ
Dedicated Hosts / Instances Long-term Compliance, licensing, or isolation needs โ€“ / Up to 70% โญโญโญโญโญ
Capacity Reservations Flexible Reserved AZ capacity without discount 0% โญโญโญโญ

3. ๐Ÿงฉ 1๏ธโƒฃ On-Demand Instances

  • Pay per second (Linux/Windows) or per hour (other OS).
  • No upfront cost, no commitment.
  • Highest flexibility, highest price.
  • Perfect for:

    • Testing, proof of concept, dev environments.
    • Unpredictable workloads.

๐Ÿ’ก Example:

โ€œRun when you want, stop when you want โ€” like renting a car by the hour.โ€


4. ๐Ÿ’ก 2๏ธโƒฃ Reserved Instances (RI)

  • Commit for 1 or 3 years.
  • Save up to 72% compared to On-Demand.
  • Fixed attributes: instance type, region, tenancy, OS.
  • Payment options:

    • No upfront
    • Partial upfront
    • All upfront (max discount)
  • Two types:

    • Standard RI โ†’ fixed configuration
    • Convertible RI โ†’ change family, OS, or size (discount ~66%)
  • Can buy/sell on AWS RI Marketplace.

โœ… Use for:
Steady workloads like databases, web servers, or ERP systems.


5. ๐Ÿ’ธ 3๏ธโƒฃ Savings Plans

  • Modern alternative to RI.
  • Commit to spend a fixed $/hour (e.g., $10/hour for 3 years).
  • AWS automatically applies discount to matching compute usage.
  • Flexibility:

    • Any instance size in same family.
    • Switch between Linux โ†” Windows.
    • Works with EC2, Fargate, Lambda.

โœ… Use for:
Dynamic environments where workload changes but total spend is predictable.

๐Ÿ’ก Analogy:

โ€œYou commit to spending $300 per month at a hotel โ€” you can change rooms anytime.โ€


6. โšก 4๏ธโƒฃ Spot Instances

  • Up to 90% cheaper than On-Demand.
  • AWS reclaims instances anytime with a 2-minute warning.
  • Ideal for workloads tolerant to interruptions:

    • Batch jobs, rendering, data analysis, CI/CD runners, machine learning training.
  • Not suited for:

    • Databases or critical systems.

๐Ÿ’ก Analogy:

โ€œLike last-minute hotel deals โ€” super cheap, but you might get kicked out anytime.โ€


7. ๐Ÿ  5๏ธโƒฃ Dedicated Hosts & Dedicated Instances

Dedicated Host

  • Physical server fully reserved for your account.
  • Visibility into underlying sockets, cores, VMs.
  • Use for:

    • Bring Your Own License (BYOL) software (Oracle, SQL Server, etc.).
    • Compliance or regulatory isolation needs.
  • Billed per host, can be reserved 1 or 3 years.

Dedicated Instance

  • Runs on hardware dedicated to you, but AWS manages placement.
  • You donโ€™t see or control the physical server.
  • Slightly cheaper than Dedicated Host.

๐Ÿ’ก Difference:

Feature Dedicated Instance Dedicated Host
Control over placement โŒ โœ…
Hardware visibility โŒ โœ…
Licensing (BYOL) support โŒ โœ…
Cost Lower Higher

8. ๐Ÿงฑ 6๏ธโƒฃ Capacity Reservations

  • Reserve capacity in a specific Availability Zone (AZ).
  • No discount โ€” billed at On-Demand rate.
  • Guarantees instance availability even during high demand.
  • Can be canceled anytime.

โœ… Use for:

  • Mission-critical workloads that must always launch.
  • Short-term events or DR (disaster recovery) readiness.

๐Ÿ’ก Analogy:

โ€œYou book a hotel room but pay even if you donโ€™t stay โ€” youโ€™re guaranteed itโ€™s there.โ€


9. ๐Ÿงฎ Cost & Use Case Comparison

Option Duration Commitment Discount Suitable For Risk of Interruption
On-Demand None None โ€“ Short, unpredictable workloads โŒ
Reserved Instance 1โ€“3 yrs Fixed Up to 72% Steady usage โŒ
Savings Plan 1โ€“3 yrs Spend commitment Up to 72% Flexible long-term โŒ
Spot Instance None Variable Up to 90% Short, interruptible โœ…
Dedicated Host 1โ€“3 yrs Fixed โ€“ Compliance, BYOL โŒ
Capacity Reservation Any None 0% Guaranteed capacity โŒ

10. ๐Ÿจ Hotel Analogy (Easiest to Remember)

Option Analogy Description
On-Demand Walk-in guest Pay full price, come and go anytime
Reserved Instance Long-term resident Pay less for committing to stay longer
Savings Plan Monthly membership Spend fixed $ each month, flexible room type
Spot Instance Last-minute deal Cheap, but may lose your room anytime
Dedicated Host Rent the whole hotel Full control, private property
Capacity Reservation Reserve a room just in case Pay even if you donโ€™t use it

11. ๐Ÿง  Exam & Interview Tips

  • โ—On-Demand โ†’ short, unpredictable, no commitment.
  • ๐Ÿ’กReserved Instance โ†’ predictable workloads (DBs, web apps).
  • ๐Ÿ’ฐSavings Plan โ†’ flexible workloads, commit to spend.
  • โš™๏ธSpot โ†’ batch, ML, non-critical compute.
  • ๐ŸงพDedicated Host โ†’ compliance or BYOL licensing.
  • ๐ŸงฉCapacity Reservation โ†’ guaranteed AZ availability.

โœ… Summary

Feature Optimized For Example
On-Demand Flexibility Dev/test, startups
Reserved Predictability Databases
Savings Plan Spending control Constant EC2 usage
Spot Cost savings Batch, analytics
Dedicated Host Compliance & licenses Oracle workloads
Capacity Reservation Availability guarantee Disaster recovery

โšก Deep Dive: EC2 Spot Instances


1. ๐ŸŽฏ Goal

Learn how EC2 Spot Instances work, how to use them safely, and how AWS manages interruptions, pricing, and automation for massive cost savings.


2. ๐Ÿ’ฐ Why Spot Instances?

  • Up to 90% cheaper than On-Demand.
  • You use unused EC2 capacity that AWS sells at a discount.
  • You must be prepared for interruptions.

โœ… Ideal for:

  • Batch jobs
  • CI/CD runners
  • Data analytics
  • ML training
  • Image/video processing
  • Container clusters (ECS, EKS)

โŒ Not ideal for:

  • Databases
  • Stateful apps
  • Long-lived sessions
  • Mission-critical production workloads

3. โš™๏ธ How Spot Pricing Works

๐Ÿ”ธ Step 1 โ€” You define:

Max Spot Price = the most youโ€™re willing to pay/hour
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”ธ Step 2 โ€” AWS publishes:

Current Spot Price (varies by instance type & AZ)
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”ธ Step 3 โ€” If:

Condition Result
Spot price โ‰ค Max price โœ… Instance runs
Spot price > Max price โš ๏ธ Instance interrupted (2-minute warning)

4. โฐ Two-Minute Interruption Notice

When AWS reclaims your instance, you get a 2-minute warning.
You can:

  1. Stop the instance โ†’ retain EBS data; restart later.
  2. Terminate the instance โ†’ lose ephemeral data; cheaper.

๐Ÿ’ก Choose based on workload type:

  • Stop โ†’ stateful compute
  • Terminate โ†’ stateless batch jobs

5. ๐Ÿงฑ Spot Blocks (Fixed-Duration Instances)

  • Lock a spot instance for 1โ€“6 hours.
  • AWS guarantees no interruption during that period (except in rare capacity loss).
  • Cost is higher than standard Spot, but still cheaper than On-Demand.

โœ… Best for predictable short jobs (e.g., nightly builds, simulations).


6. ๐Ÿ“ˆ Spot Price Behavior

  • Prices fluctuate by Availability Zone and instance family.
  • Reflect supply and demand โ€” not user bidding anymore (AWS sets the price).
  • Typically stable, but may spike if capacity tightens.

๐Ÿ’ก Example:
m4.large On-Demand: $0.10/hr
Spot average: ~$0.04/hr โ†’ 60%+ savings


7. ๐Ÿงฉ Spot Requests

A Spot Request defines:

  • Number of instances
  • Max price
  • AMI, instance type, subnet
  • Duration (valid from/until)
  • Request type โ†’ One-Time or Persistent

๐Ÿ”น One-Time Request

  • Launches once โ†’ fulfilled โ†’ ends automatically.
  • Good for single batch jobs.

๐Ÿ”น Persistent Request

  • Stays open until canceled.
  • If an instance is terminated due to price/capacity, AWS automatically relaunches new ones when conditions improve.

8. โŒ How to Cancel Spot Requests Properly

โš ๏ธ Order matters:

  1. Cancel the Spot Request โ†’ Prevents AWS from launching replacements.
  2. Terminate the Spot Instances โ†’ Frees resources youโ€™re billed for.

If you terminate first (without canceling),
the Spot Request sees โ€œ0 instances runningโ€ and relaunches them again.

โœ… Exam Tip โ†’ Always cancel request first, then terminate instances.


9. ๐Ÿš€ Spot Fleets

A Spot Fleet = group of Spot + (optional) On-Demand instances that AWS manages to meet a target capacity at lowest possible cost.

๐Ÿ“ฆ What You Define

  • Target capacity (e.g., 100 vCPUs or 10 instances)
  • Multiple launch pools:

    • Different instance types
    • Different AZs
    • Different OSs
  • Allocation strategy (below)

โš™๏ธ Allocation Strategies

Strategy Description Best For
Lowest-Price Chooses the cheapest pool Cost-optimized short workloads
Diversified Spreads across multiple pools Availability-focused, long workloads
Capacity-Optimized Chooses pools with best capacity Large-scale, reliable compute
Price-Capacity-Optimized Balances lowest price + available capacity ๐Ÿ”น Best for most real workloads

โœ… AWS automatically replaces lost instances to maintain capacity.


10. ๐Ÿ”„ Spot Fleet vs Simple Spot Request

Feature Spot Request Spot Fleet
Single instance type โœ… โŒ
Multiple instance types โŒ โœ…
Across multiple AZs โŒ โœ…
Includes On-Demand โŒ โœ…
Auto-optimization โŒ โœ…
Best for Simple job Cost-optimized scaling cluster

๐Ÿ’ก Think of Spot Fleet as an intelligent manager that keeps your compute capacity running at the lowest possible cost.


11. ๐Ÿ’ก Practical Examples

Use Case Best Approach
Hadoop/Spark batch jobs Spot Fleet (diversified)
CI/CD pipelines Spot Block (1โ€“6 hrs)
ML model training Spot Fleet (price-capacity-optimized)
Web servers with ASG Combine On-Demand + Spot mix
Databases Never use Spot

12. ๐Ÿง  Exam & Interview Tips

  • Spot = cheapest but interruptible.
  • 2-minute warning before termination.
  • Spot Block = 1โ€“6 hr fixed duration.
  • Cancel request โ†’ then terminate instances.
  • Spot Fleet optimizes across types, AZs, and prices.
  • Price-Capacity-Optimized = best modern default.
  • Donโ€™t use Spot for critical or stateful systems.

โœ… Summary

Feature Description
Max discount Up to 90%
Billing unit Per second
Interruption notice 2 minutes
Typical use cases Batch, analytics, CI/CD
Donโ€™t use for Databases, critical workloads
Key services Spot Request, Spot Fleet
Recommended strategy Price-Capacity-Optimized

๐Ÿš€ All the Ways to Launch EC2 Instances


1. ๐ŸŽฏ Goal

Understand every method AWS offers to launch EC2 instances, from Spot Requests to Dedicated Hosts, and when each is appropriate for cost, flexibility, or compliance.


2. โšก Option 1 โ€” Spot Requests

๐Ÿ’ฐ Save up to 90% on compute costs!

A Spot Request asks AWS for spare EC2 capacity at discounted pricing.

๐Ÿงญ Steps in the Console

  1. In the EC2 Dashboard, go to Spot Requests.
  2. Click Pricing history โ†’ view past 3 months for any instance type (e.g., c4.large).
  • Black bar = On-Demand price.
  • Colored lines = Spot prices per AZ.
  • Typically 60โ€“70% cheaper and quite stable.

๐Ÿงฑ Create a Spot Request

Click Request Spot Instances โ†’ You can either:

  • Use a Launch Template, or
  • Manually configure launch settings:

    • AMI (e.g., Amazon Linux 2)
    • Key pair
    • VPC/subnet
    • Security group

โš™๏ธ Request Details

Setting Description
Max Price Max hourly rate youโ€™re willing to pay. If AWSโ€™s Spot price rises above this, the instance is stopped or terminated.
Valid From / Valid Until Defines the active time window of your request.
Terminate when expired Decide whether to stop instances when request expires.
Load Balancer/Target Group (Optional) attach to ELB/ALB target group.

๐Ÿ“Š Target Capacity

  • Define how many instances or vCPUs you want.
  • Choose to maintain capacity โ€” AWS will automatically re-launch if any are lost.
  • Interruption behavior: terminate, stop, or hibernate.

๐ŸŒ Networking

  • Choose VPC, subnet, and Availability Zone (AZ).
  • Pick instance types manually (e.g., c3.large, c4.large) or define attribute filters:

    • Min/max vCPUs
    • Min/max memory
    • Architecture, virtualization type, etc.

๐Ÿ’ก The broader your filters โ†’ the more flexibility โ†’ the cheaper AWS can provide capacity.


๐Ÿงฎ Allocation Strategy

Strategy Description Use Case
Lowest Price Choose pools with lowest Spot price Short workloads, max savings
Capacity Optimized Prefer pools with highest capacity Large workloads
Diversified Spread across multiple pools High availability
Price-Capacity Optimized Mix of cost + reliability โœ… Recommended for most users

You can also maintain a diverse pool of instance types for resilience.


๐Ÿงพ Example

Target capacity: 10 instances
Estimated fleet cost: $0.156/hr
Savings: ~73% vs On-Demand


3. โšก Option 2 โ€” Launching Spot Instances Directly

Instead of Spot Fleet, you can launch directly from:
EC2 โ†’ Instances โ†’ Launch Instance โ†’ Advanced details โ†’ Request Spot Instances

Youโ€™ll see options:

  • Request type: one-time (default) or persistent
  • Max price: default = On-Demand price (can customize)
  • Interruption behavior: stop, terminate, hibernate
  • Request validity: specify start & end time

๐Ÿ’ก The โ€œblock durationโ€ (1โ€“6 hour Spot blocks) feature was deprecated after Dec 2022.


4. ๐Ÿ’ธ Option 3 โ€” Reserved Instances (RI)

Buy capacity in advance for 1 or 3 years.

Console Flow:

  1. EC2 โ†’ Reserved Instances
  2. Search instance type (e.g., c5.large)
  3. Choose:
  • Term: 12 or 36 months
  • Type: Standard or Convertible
  • Payment: All Upfront / Partial / No Upfront
    1. Add to Cart โ†’ View Cart โ†’ (โš  donโ€™t actually purchase unless needed!)

๐Ÿ’ก Convertible RIs let you change instance family/OS.
Standard RIs are locked but cheaper.

โš ๏ธ Note: RIs are slowly being replaced by Savings Plans.


5. ๐Ÿ’ก Option 4 โ€” Savings Plans

A modern alternative to RIs, committing to spend a fixed $ per hour over 1โ€“3 years.

Features

  • Flexible across:

    • Instance size
    • OS
    • Region
    • Tenancy (default, dedicated, host)
  • Applies to EC2, Fargate, and Lambda usage.

  • Same savings as RIs (up to 72%).

โœ… Recommended for most long-term, steady workloads.


6. ๐Ÿ  Option 5 โ€” Dedicated Hosts

Get a physical EC2 server fully reserved for your account.

Use Cases

  • Compliance or regulatory isolation.
  • BYOL (Bring Your Own License) software (Oracle, SQL Server).
  • Control instance placement and underlying hardware.

Launch Steps

  1. EC2 โ†’ Dedicated Hosts โ†’ Allocate Dedicated Host
  2. Select:
  • Instance family (e.g., c5)
  • Availability Zone
    1. Click Allocate

โš ๏ธ Cost is much higher โ€” typically for enterprise or compliance workloads.


7. ๐Ÿงฑ Option 6 โ€” Capacity Reservations

Guarantee EC2 capacity in a specific Availability Zone (AZ) โ€” even if youโ€™re not running anything yet.

Features

  • Pay On-Demand price (no discount).
  • Reserve exact instance type & count.
  • Duration: open-ended or fixed end time.
  • Cancelling stops future billing, but youโ€™re charged while reserved.

โœ… Useful for:

  • Disaster recovery (DR)
  • Mission-critical systems
  • Short-term but guaranteed compute bursts

Example:

Reserve 4 ร— m5.2xlarge in eu-central-1a
โ†’ You pay even if not used, but AWS guarantees capacity exists.


8. ๐Ÿง  Comparison Summary

Option Pricing Commitment Flexibility Use Case
On-Demand High None Very high Unpredictable workloads
Spot Lowest None Moderate Batch, analytics, non-critical
Reserved Low 1โ€“3 yrs Fixed Databases, web servers
Savings Plan Low 1โ€“3 yrs High Steady spend, variable workload
Dedicated Host Very high Optional Low Licensing, compliance
Capacity Reservation On-Demand None Moderate Guaranteed AZ capacity

9. ๐Ÿ’ก Exam Tips

  • Spot Instance: Interrupted โ†’ 2-min warning.
  • Spot Fleet: Combines pools for lowest cost.
  • Reserved Instance: Locked to type + region.
  • Convertible RI: Can change instance family.
  • Savings Plan: Commit to spend $, flexible.
  • Dedicated Host: Physical isolation.
  • Capacity Reservation: Pay to reserve compute in an AZ.
  • Spot Block: Deprecated after Dec 2022.

โœ… Summary

AWS provides six different launch paths for EC2:

  1. Spot Request / Fleet (lowest cost)
  2. Regular Launch โ†’ request Spot Instance
  3. Reserved Instance
  4. Savings Plan
  5. Dedicated Host
  6. Capacity Reservation

Each one balances price, predictability, and flexibility differently.

Top comments (0)