This lesson combines 3 topics: AWS CLI and SDK, EC2 Basics, EC2 Pricing Models.
Learning Objectives
- Install and configure AWS CLI v2
- Understand the Credentials Provider Chain
- Know how to use Named Profiles and MFA with the CLI
- Distinguish the CLI, SDK, CloudShell, and CDK
- Understand the EC2 instance lifecycle and its basic components
- Distinguish the Instance Families (General, Compute, Memory, Storage)
- Know AMIs, User Data, Instance Metadata, and Key Pairs
- Understand Security Groups for EC2
- Understand the 5 EC2 pricing models in detail
- Know when to use RIs vs Savings Plans vs Spot
- Understand Dedicated Host vs Dedicated Instance
- Apply a pricing model to each workload pattern
Part 1: AWS CLI and SDK
1. AWS CLI (Command Line Interface)
Definition
The AWS CLI is a command-line tool for interacting with AWS services through their APIs.
Versions
- AWS CLI v2 (recommended) — bundled Python, faster, better UX
- AWS CLI v1 — legacy, about to be deprecated
Installation
# macOS
brew install awscli
# Or:
curl "https://awscli.amazonaws.com/AWSCLIV2.pkg" -o "AWSCLIV2.pkg"
sudo installer -pkg AWSCLIV2.pkg -target /
# Linux
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip && sudo ./aws/install
# Windows: download the MSI installer from https://aws.amazon.com/cli/
# Verify
aws --version
# Output: aws-cli/2.x.x Python/3.x.x ...
2. Configure CLI
Option 1: aws configure (the simplest)
$ aws configure
AWS Access Key ID [None]: AKIAxxxxxxxxxxxx
AWS Secret Access Key [None]: xxxxxxxxxxxxxxxxxxxx
Default region name [None]: us-east-1
Default output format [None]: json
→ Creates 2 files:
~/.aws/credentials(holds the keys)~/.aws/config(holds the region and output format)
File structure
# ~/.aws/credentials
[default]
aws_access_key_id = AKIAxxxxxxxxxxxx
aws_secret_access_key = xxxxxxxxxxxxxxxxxxxx
[dev]
aws_access_key_id = AKIAyyyyyyyyyyyy
aws_secret_access_key = yyyyyyyyyyyyyyyyyyyy
# ~/.aws/config
[default]
region = us-east-1
output = json
[profile dev]
region = ap-southeast-1
output = table
Using a Named Profile
# Default profile
aws s3 ls
# Specific profile
aws s3 ls --profile dev
# Or via env var
export AWS_PROFILE=dev
aws s3 ls
3. Credentials Provider Chain
The AWS CLI/SDK looks for credentials in the following priority order (stopping at the first one found):
Best practice
- Local dev: IAM Identity Center (
aws configure sso) or a named profile - EC2: IAM Role attached to the instance (no hard-coded keys)
- ECS/Fargate: Task Role
- Lambda: Execution Role
- CI/CD: OIDC federation (GitHub Actions, GitLab) instead of long-lived keys
4. CLI Output Formats
# JSON (default)
aws ec2 describe-instances
# Table (human-readable)
aws ec2 describe-instances --output table
# Text (tab-separated)
aws ec2 describe-instances --output text
# YAML
aws ec2 describe-instances --output yaml
Filter and Query
# --filters: server-side filter (saves bandwidth)
aws ec2 describe-instances \
--filters "Name=instance-state-name,Values=running"
# --query: client-side JMESPath (filters after receiving the response)
aws ec2 describe-instances \
--query 'Reservations[*].Instances[*].[InstanceId,InstanceType,State.Name]'
# Combined
aws ec2 describe-instances \
--filters "Name=tag:Environment,Values=production" \
--query 'Reservations[*].Instances[*].InstanceId' \
--output text
5. MFA with the CLI
When an IAM user requires MFA, the CLI needs a temporary token:
# Get temporary credentials with MFA
aws sts get-session-token \
--serial-number arn:aws:iam::111111111111:mfa/alice \
--token-code 123456 \
--duration-seconds 3600
# Response:
# {
# "Credentials": {
# "AccessKeyId": "ASIA...",
# "SecretAccessKey": "...",
# "SessionToken": "...",
# "Expiration": "..."
# }
# }
Or configure a profile that auto-prompts for MFA:
# ~/.aws/config
[profile dev-mfa]
mfa_serial = arn:aws:iam::111111111111:mfa/alice
role_arn = arn:aws:iam::222222222222:role/CrossAccountRole
source_profile = default
aws s3 ls --profile dev-mfa
# The CLI will prompt: Enter MFA code:
6. AWS CloudShell
Definition
CloudShell is a browser-based shell in the AWS Console, with the AWS CLI, Python, Node.js, and Git preinstalled.
Characteristics
- Free (no EC2 cost)
- 1 GB persistent storage per Region (stores the home directory)
- Automatically authenticated with your current console identity
- Available in some Regions (us-east-1, eu-west-1, ap-southeast-1...)
- Idle timeout: 20-30 minutes
Use cases
- Run AWS CLI commands quickly without a local setup
- Learn the AWS CLI in a safe environment
- Quick scripts without a local environment
7. AWS SDK
Definition
An SDK (Software Development Kit) is a library that lets an application call AWS APIs from code.
Main SDKs
| Language | Package |
|---|---|
| Python | boto3 |
| JavaScript/Node.js | @aws-sdk/client-* (v3 modular) |
| Java | aws-sdk-java-v2 |
| .NET | AWSSDK.* (NuGet) |
| Go | github.com/aws/aws-sdk-go-v2 |
| PHP, Ruby, C++, Rust... | Available |
Python boto3 example
import boto3
# Create an S3 client (auto picks credentials from the provider chain)
s3 = boto3.client('s3', region_name='us-east-1')
# List buckets
response = s3.list_buckets()
for bucket in response['Buckets']:
print(bucket['Name'])
# Upload file
s3.upload_file('local.txt', 'my-bucket', 'remote.txt')
# Resource API (higher-level)
s3_res = boto3.resource('s3')
bucket = s3_res.Bucket('my-bucket')
for obj in bucket.objects.all():
print(obj.key)
8. AWS CDK (Cloud Development Kit) — Concepts
Definition
CDK lets you define infrastructure in code (TypeScript, Python, Java, C#, Go) instead of CloudFormation YAML/JSON.
Workflow
CDK code (TypeScript)
│
▼
cdk synth → CloudFormation template (JSON/YAML)
│
▼
cdk deploy → AWS CloudFormation creates resources
Advantages over plain CloudFormation
- Type safety, autocomplete
- Reusable constructs (L1/L2/L3)
- Loops, conditionals (logic of a real programming language)
- Testing with a unit test framework
9. Comparing the tools
| Tool | When to use |
|---|---|
| AWS Console | Explore services, quick clicks |
| AWS CLI | Scripts, automation, CI/CD |
| AWS SDK | Build applications |
| AWS CloudShell | CLI without local setup |
| CloudFormation | Declarative IaC (JSON/YAML) |
| AWS CDK | Programmatic IaC (code) |
| Terraform | Multi-cloud IaC (3rd party) |
10. Common CLI Commands cheatsheet
# S3
aws s3 ls
aws s3 cp file.txt s3://my-bucket/
aws s3 sync ./local s3://my-bucket/path/
# EC2
aws ec2 describe-instances
aws ec2 start-instances --instance-ids i-xxxx
aws ec2 stop-instances --instance-ids i-xxxx
aws ec2 run-instances --image-id ami-xxx --instance-type t3.micro
# IAM
aws iam list-users
aws iam list-roles
aws iam get-user
# STS (Security Token Service)
aws sts get-caller-identity # "Whoami" for AWS
# CloudFormation
aws cloudformation deploy --template-file stack.yaml --stack-name my-stack
# Help
aws help # Top-level help
aws s3 help # Service help
aws s3 cp help # Command help
Part 2: EC2 Basics
1. EC2 Overview
EC2 (Elastic Compute Cloud) is an IaaS service that provides on-demand virtual servers (instances).
Why use EC2
- Full control over the OS, network, and storage
- A wide range of instance types (CPU, RAM, GPU, storage)
- Pay per second (Linux) or per hour (Windows)
- Scale up/down quickly
2. Instance Lifecycle
Comparing the states
| State | Compute charge | EBS charge | Public IP |
|---|---|---|---|
| running | Yes | Yes | Yes (if assigned) |
| stopped | No | Yes | Public IP is lost (Elastic IP is kept) |
| stopping (hibernate) | No | Yes | — |
| terminated | No | Volume deleted automatically (if DeleteOnTermination=true) | All lost |
| reboot | Charged as normal | — | Keeps Public IP, private IP, EBS |
Stop vs Terminate
- Stop: Saves state, can be started again. The Instance ID stays the same. The EBS root remains.
- Terminate: Deletes the instance permanently. By default the EBS root is deleted too.
Hibernate (special case)
- Saves RAM to the EBS root; on restart the RAM state is preserved
- Requirements: the EBS root must be encrypted and large enough to hold the RAM; instance RAM < 150 GB (the limit is on RAM, not on EBS root size); the instance family and OS must support it
- Use case: Fast resume of an app with a warm cache
3. Instance Families
Naming overview: m5.xlarge
Main families
| Family | Type | Use case | Examples |
|---|---|---|---|
| T | Burstable | Web servers, dev, low traffic | t3, t3a, t4g |
| M | General purpose | Balanced CPU/RAM | m5, m6i, m7g |
| C | Compute-optimized | Batch, gaming, scientific | c5, c6i, c7g |
| R | Memory-optimized | In-memory DB, real-time analytics | r5, r6i, x2idn |
| X | High memory | SAP HANA, large in-memory DB | x1, x2 |
| I | Storage (NVMe SSD) | NoSQL, data warehouse | i3, i4i |
| D | Storage (HDD) | Distributed file systems, Hadoop | d2, d3 |
| G/P | GPU | Machine learning, graphics | g4dn, p4d |
| F | FPGA | Genomics, financial analytics | f1 |
| Inf | AWS Inferentia | ML inference | inf1, inf2 |
| Trn | AWS Trainium | ML training | trn1 |
Graviton (ARM-based)
- Suffix
g= ARM Graviton (custom AWS chip): t4g, m6g, c7g, r7g - 20% cheaper vs x86, more power-efficient
- Requires ARM64-compatible applications
Burstable (T family) specifics
- Accumulates CPU credits while idle
- Spends credits when bursting up to 100% CPU
- 2 modes:
- Standard: When credits run out, performance drops to the baseline
- Unlimited (default for t3/t4g): Going above the baseline incurs extra charges
4. AMI (Amazon Machine Image)
Definition
An AMI is a template containing the OS, application, and configuration used to launch EC2.
4 AMI sources
| Type | Description |
|---|---|
| Quick Start | AWS official: Amazon Linux 2023, Ubuntu, Windows Server, RHEL |
| AWS Marketplace | Third-party: Bitnami, vendors (software may be paid) |
| Community AMI | Public AMIs from other users (be careful about security) |
| My AMIs | AMIs you create (custom golden image) |
Creating a Custom AMI
- Launch EC2 from a base AMI
- Install and configure
- Console: Actions → Image → Create Image
- The AMI can be shared cross-account or made public
EBS-backed vs Instance Store-backed AMI
| AMI type | Boot time | Persistence | Stop possible |
|---|---|---|---|
| EBS-backed | Fast | Persistent (EBS) | Can be stopped |
| Instance Store-backed | Slower | Lost on terminate | Cannot be stopped, only terminated |
Most modern AMIs are EBS-backed.
AMI Region
- An AMI is regional — it exists only in the Region where it was created
- Cross-Region: Copy the AMI to another Region (copy charges apply)
5. User Data
Definition
User Data is a script that runs the first time an EC2 instance boots, used to bootstrap the instance.
Use cases
- Install packages (Apache, Node.js)
- Pull code from Git
- Configure the CloudWatch agent
- Join an Active Directory domain
Linux bash script example
#!/bin/bash
yum update -y
yum install -y httpd
systemctl start httpd
systemctl enable httpd
echo "<h1>Hello from $(hostname -f)</h1>" > /var/www/html/index.html
Characteristics
- Runs with root privileges
- Runs only once at launch (by default)
- Logged at
/var/log/cloud-init-output.log - Max size: 16 KB (base64-encoded)
- Can be edited while the instance is stopped
6. Instance Metadata Service (IMDS)
Definition
An internal EC2 service that provides metadata about the instance via the endpoint http://169.254.169.254/.
Examples
# Get the instance ID
curl http://169.254.169.254/latest/meta-data/instance-id
# Output: i-0123456789abcdef0
# Get the public IP
curl http://169.254.169.254/latest/meta-data/public-ipv4
# Get IAM role credentials
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/MyRole
IMDSv1 vs IMDSv2
| Feature | IMDSv1 | IMDSv2 |
|---|---|---|
| Auth | None | Session token (PUT request) |
| Vulnerability | SSRF attacks | Protects against SSRF |
| Status | Legacy | Default and strongly recommended to require |
IMDSv2 workflow
# 1. Get a session token (TTL 6 hours max)
TOKEN=$(curl -X PUT "http://169.254.169.254/latest/api/token" \
-H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
# 2. Call metadata with the token
curl -H "X-aws-ec2-metadata-token: $TOKEN" \
http://169.254.169.254/latest/meta-data/instance-id
Best practice
- Set IMDS to "Required" (v2 only) at instance launch
- Disable IMDS entirely if you do not need it
7. Key Pair (SSH)
Definition
A Key Pair is used to SSH (Linux) or RDP (Windows) into EC2.
Types
- RSA (legacy)
- ED25519 (modern, recommended)
Workflow
- Create a key pair in the AWS Console or import a public key
- Download the
.pemfile (you can download it only once) chmod 400 my-key.pem- SSH:
ssh -i my-key.pem ec2-user@<public-ip>
Lost your key pair?
- It cannot be recovered from AWS
- Workarounds:
- Create a new AMI with a different key
- Detach the root volume, mount it on another instance, edit
~/.ssh/authorized_keys - Use EC2 Instance Connect or Systems Manager Session Manager
EC2 Instance Connect
- Browser-based SSH from the AWS Console
- Temporarily pushes a public key to the instance via the API
- No local
.pemfile needed
8. Security Group
Definition
A Security Group is a virtual firewall at the instance level (attached to the ENI).
Characteristics
- Stateful: response traffic is allowed automatically
- Allow rules only (no Deny rules)
- Default: deny all inbound, allow all outbound
- Can reference another SG as the source/destination
- Up to 5 SGs/ENI, 60 inbound + 60 outbound rules/SG
Example SG for a web server
Comparison with NACLs (covered in detail in Week 2 Day 1, Part 3)
| Security Group | NACL | |
|---|---|---|
| Scope | Instance (ENI) | Subnet |
| State | Stateful | Stateless |
| Rules | Allow only | Allow + Deny |
9. Placement Groups
3 strategies
| Strategy | Use case | Limit |
|---|---|---|
| Cluster | HPC, low-latency between instances | 1 AZ |
| Spread | Critical apps, isolation | Max 7 instances/AZ |
| Partition | Distributed systems (HDFS, Kafka) | Up to 7 partitions/AZ |
10. Tags
EC2 supports resource tags (up to 50 tags/resource):
Name=WebServer-ProdEnvironment=productionOwner=alice@company.comCostCenter=CC-1234
Tags are used for:
- Cost allocation
- ABAC (attribute-based access control)
- Auto Scaling filtering
- AWS Backup selection
Part 3: EC2 Pricing Models
1. Overview of the 5 Pricing Models
| Model | Discount | Commitment | Refund/exit | Use case |
|---|---|---|---|---|
| On-Demand | 0% | None | — | Test, unpredictable, short-term |
| Reserved Instance (RI) | Up to 72% | 1y / 3y | Can be resold on the Marketplace | Steady workload |
| Savings Plans (SP) | Up to 72% | 1y / 3y | Non-refundable | Flexible commitment |
| Spot Instance | Up to 90% | None | EC2 can be reclaimed | Fault-tolerant, batch |
| Dedicated Host | — | On-demand or RI | — | License BYOL, compliance |
2. On-Demand
Characteristics
- Billed per second (Linux, min 60s) or per hour (Windows, RHEL, SLES)
- No commitment
- The most expensive but the most flexible
Use cases
- Short-term test/development
- Unpredictable workloads
- Early migration phase (exact requirements not yet known)
- Temporary load peaks (alongside RIs for the baseline)
3. Reserved Instance (RI)
Term
- 1 year or 3 years
- 3 years saves more than 1 year
Payment options
- All Upfront (AURI): Pay everything → largest discount
- Partial Upfront (PURI): Pay part → medium discount
- No Upfront (NURI): Pay monthly → lower discount
Offering Class
| Class | Change instance family | Change OS, tenancy | Resell on Marketplace |
|---|---|---|---|
| Standard RI | No | No | Yes |
| Convertible RI | Yes (equal or greater value) | Yes | No |
Scope
- Regional RI (default): Applies to any AZ in the Region, does not reserve capacity
- Zonal RI: Applies to 1 specific AZ, reserves capacity (guarantees an instance when you need it)
Use cases
- Workloads running steadily 24/7 for > 1 year
- Production databases
- Stable web servers (same baseline + ASG for peaks)
Reserved Instance Marketplace
- Sell Standard RIs you no longer need
- Buyers can purchase RIs with < 1 year remaining from the Marketplace
4. Savings Plans (SP)
Definition
Savings Plans = commit to $X/hour for 1 or 3 years and get a discount on the matching usage.
3 types of SP
| Type | Applies to | Flexibility | Discount |
|---|---|---|---|
| Compute Savings Plans | EC2 (any family, Region), Fargate, Lambda | Highest | Up to 66% |
| EC2 Instance Savings Plans | EC2 1 family + 1 Region | Change size/OS within the family | Up to 72% |
| SageMaker Savings Plans | SageMaker | — | Up to 64% |
RI vs Savings Plans
| Reserved Instance | Savings Plans | |
|---|---|---|
| Commitment | Instance attributes (type, OS, region) | $/hour spend |
| Apply to | EC2, RDS, ElastiCache, OpenSearch, Redshift | EC2 + Fargate + Lambda (Compute SP) |
| Flexibility | Convertible RI allows changes | High (Compute SP changes family, region) |
| Resell | Standard RI can be resold | Cannot be resold |
Recommendation: Compute Savings Plans for EC2 + serverless workloads.
5. Spot Instances
Definition
Spot = buying spare EC2 capacity at up to 90% off compared with On-Demand, but AWS can reclaim it with a 2-min warning.
Spot Price
- The price changes with supply and demand
- You set a maximum price (your bid)
- If Spot Price ≤ max price → the instance runs
- If Spot Price > max price → the instance is terminated
Spot Instance Interruption Behavior
3 options when reclaimed:
- Terminate (default)
- Stop (keeps EBS)
- Hibernate (saves RAM)
Spot Fleet vs Spot Request
| Spot Request | Spot Fleet | |
|---|---|---|
| Number of instances | 1 | Multiple, mix On-Demand + Spot |
| Allocation strategy | — | lowest-price, diversified, capacity-optimized |
Allocation Strategy (for Spot Fleet & mixed ASGs)
- lowestPrice: The pool with the lowest price
- diversified: Spread across many pools
- capacityOptimized: The pool least likely to be interrupted (recommended)
- priceCapacityOptimized: Balances price + capacity
Spot use cases
- Batch processing
- Big data (EMR, Spark)
- CI/CD workers
- Containerized stateless workloads (ECS/EKS)
- Image/video rendering
- DO NOT use for: Databases, single-instance critical apps
Spot Block (deprecated)
- Previously: Spot reserved for 1-6 hours without being reclaimed
- AWS discontinued Spot Block for new customers in 2021. Only regular Spot Requests remain.
6. Dedicated Host
Definition
A Dedicated Host = a physical server dedicated to 1 account, with visibility down to the socket/core level.
Characteristics
- You pay per host (not per instance)
- Visibility into CPU sockets and physical cores
- License BYOL (Bring Your Own License) for Windows Server, SQL Server, Oracle
- Compliance (regulations require dedicated hardware)
- Supports Host Affinity: the instance always launches on the same host across stop/start
Pricing
- On-Demand Dedicated Host: $/hour
- Reserved Dedicated Host: 1y/3y term, discount up to ~70%
7. Dedicated Instance
Definition
A Dedicated Instance = an EC2 instance running on hardware dedicated to 1 account, but you have no visibility down to the socket.
Dedicated Host vs Dedicated Instance
| Dedicated Host | Dedicated Instance | |
|---|---|---|
| Pricing | Per host | Per instance |
| Hardware visibility | Yes (socket, core) | No |
| BYOL | Yes | Limited |
| Same host across stop/start | Yes (Host Affinity) | Not guaranteed |
| Use case | Strict compliance, BYOL | Moderate compliance |
8. Capacity Reservations
Definition
An On-Demand Capacity Reservation (ODCR) = reserves EC2 capacity in 1 specific AZ, with no price discount, it only guarantees capacity when you need it.
Use cases
- Guarantee capacity for important events (Black Friday)
- DR scenarios (guarantee capacity for failover)
- Combination: ODCR + Savings Plans = capacity + discount
Comparison
| Zonal RI | On-Demand Capacity Reservation | |
|---|---|---|
| Discount | Yes | No |
| Capacity guarantee | Yes | Yes |
| Commitment | 1y/3y | None (can cancel anytime) |
9. Overall comparison — Which pricing to choose?
Best practice mix
Baseline workload (24/7) → RI or Compute SP
Variable workload → On-Demand
Burst/batch → Spot
Web app example:
- 10 baseline instances → 10 RI 3-year (~72% off)
- 5 instances during peak hours → On-Demand
- Background processing → Spot
10. Cost Comparison Exercise
Scenario: EC2 t3.medium running 24/7 for 3 years in us-east-1.
| Pricing | Price $/hour | 3-year total | Savings |
|---|---|---|---|
| On-Demand | $0.0416 | ~$1,093 | 0% |
| RI 1-year NURI | $0.029 | ~$762 | 30% |
| RI 3-year AURI | $0.0134 | ~$352 | 68% |
| Compute SP 3-year AURI | $0.014 | ~$368 | 66% |
| Spot (avg) | $0.013 | ~$341 | 69% (but can be reclaimed) |
Prices vary by region and over time — this is only an illustration.
Review Questions
-
An EC2 instance needs to access S3 — how should you configure credentials?
Show answer
Attach an IAM Role (Instance Profile) to the EC2 instance. The SDK/CLI on the instance automatically obtains temporary credentials from the Instance Metadata Service (IMDSv2) at
http://169.254.169.254. Nothing else needs to be configured in code — credentials are rotated automatically every hour. Never hard-code an Access Key ID/Secret in code, config files, or environment variables on the server. -
List the priority order in the Credentials Provider Chain (top 3).
Show answer
(1) Command-line options (
--access-key,--secret-key) — highest. (2) Environment variables (AWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEY,AWS_SESSION_TOKEN). (3) IAM Identity Center session (aws configure sso; formerly AWS SSO). Next: Web Identity Token, shared credentials file (~/.aws/credentials), config file, container credentials, EC2 Instance Profile. The chain stops at the first entry found. -
Is AWS CloudShell charged?
Show answer
Free. CloudShell has no separate compute charge. You get 1 GB of free persistent storage per Region (home directory). You are only charged if CloudShell makes AWS API calls that create resources (for example launching EC2) — but the shell itself has no cost. It is automatically authenticated with the identity signed in to the Console.
-
What is the difference between
--filtersand--queryin the AWS CLI?Show answer
--filtersis server-side filtering — AWS applies the filter before returning the response, saving bandwidth and time with large datasets.--queryis client-side filtering (JMESPath) — AWS returns the full response and the CLI filters locally. Combine both:--filtersreduces data from the server,--queryextracts the fields you need from the response.--filtersonly works with fields AWS supports for filtering;--queryis more flexible with any field in the JSON. -
How does CDK differ from CloudFormation?
Show answer
CDK lets you define infrastructure in a programming language (TypeScript, Python, Java, Go...) with type safety, autocomplete, loops, conditionals, and unit tests. CDK compiles to a CloudFormation template (
cdk synth) and then deploys through CloudFormation. Plain CloudFormation uses declarative YAML/JSON — more verbose and without programming logic. CDK has L2/L3 constructs (high-level abstractions) that let you write less code for common patterns. -
What is the difference between Stop and Terminate for EC2?
Show answer
Stop: the instance shuts down but still exists and can be started again. The EBS root volume is kept. The Public IP is lost (but an Elastic IP is kept). No compute charge while stopped, but EBS is still charged. Terminate: the instance is deleted permanently. The EBS root volume is deleted (if
DeleteOnTermination=true). It cannot be undone. Use Stop to pause; Terminate to delete for good. -
What is special about the T-family compared with the M-family?
Show answer
The T-family (t3, t4g) uses a burstable CPU model: the instance accumulates "CPU credits" while idle and spends them to burst to high CPU when needed. Suitable for uneven workloads (web dev server, small DB). The M-family (m6i, m7g) provides dedicated, consistent CPU — no credit mechanism. The M-family suits steady workloads such as production web servers that need stable CPU.
-
What advantages does an EBS-backed AMI have over an Instance Store-backed one?
Show answer
EBS-backed AMI: you can Stop the instance (data persists on EBS), it boots faster (boots from an EBS snapshot), it is easy to create AMI snapshots, and the root volume can be detached. Instance Store-backed: data is lost on stop/terminate (ephemeral) — it only exists while running. EBS-backed is the default choice and suits most use cases.
-
How does IMDSv2 differ from IMDSv1 in terms of security?
Show answer
IMDSv1 allows metadata to be called directly without authentication — vulnerable to SSRF (Server-Side Request Forgery) attacks: an attacker exploits SSRF to steal IAM credentials from the metadata endpoint. IMDSv2 requires a session token (obtained first via a PUT request) — typical SSRF cannot make PUT requests, which prevents SSRF credential theft. Enforcing IMDSv2 (Required) on all instances is recommended.
-
When should you use a Cluster vs a Spread Placement Group?
Show answer
Cluster Placement Group: all instances in the same AZ, on the same rack hardware, connected by a 10 Gbps+ network. Use it for HPC, big data, and low-latency applications that need high network bandwidth (Hadoop, ML training). Risk: a single hardware failure can affect many instances. Spread Placement Group: each instance on separate hardware, possibly across AZs. Use it for critical applications that need maximum HA — up to 7 instances/AZ/group.
- How do Standard and Convertible RIs differ?
Show answer
Standard RI: higher discount (up to 72%), cannot change instance family/OS/tenancy during the term, can be resold on the RI Marketplace. Convertible RI: lower discount (~54%), can be exchanged for another RI of equal or greater value (change instance family, OS, tenancy — cannot change the Region or term, the RI is tied to the Region), cannot be resold. Choose Standard when the workload is clearly stable; Convertible when you need flexibility.
- When should you use Compute Savings Plans instead of EC2 Instance Savings Plans?
Show answer
Compute Savings Plans apply to EC2 (any instance family, Region, OS, tenancy), Lambda, and Fargate — the most flexible but with a lower discount (~66%). EC2 Instance Savings Plans apply only to one instance family in a specific Region — higher discount (~72%) but less flexible. Choose Compute SP when you have significant Lambda/Fargate workloads or need to change instance families; EC2 Instance SP when the EC2 workload is stable and the instance family is well known.
- How much warning do you get before AWS reclaims a Spot Instance?
Show answer
2 minutes (120 seconds) of warning before AWS reclaims it. The Spot Instance sends an interruption notice via Instance Metadata and EventBridge. The application must handle it gracefully within these 2 minutes: checkpoint work, drain connections, save state. Spot suits batch jobs, data processing, and stateless workloads — not databases or stateful apps that cannot tolerate interruption.
- Which use case REQUIRES a Dedicated Host instead of a Dedicated Instance?
Show answer
BYOL (Bring Your Own License) for software licensed per physical server or per-socket/per-core — for example Windows Server, SQL Server, Oracle Database with license models based on physical host specs. A Dedicated Host provides visibility into the number of cores and sockets on a specific physical server — needed to comply with license terms. A Dedicated Instance only guarantees isolated hardware but does not provide host-level visibility.
- Does an On-Demand Capacity Reservation give a price discount?
Show answer
No. An On-Demand Capacity Reservation guarantees reserved capacity in a specific AZ but is charged at the On-Demand rate — no discount. To get both a capacity reservation and a discount, combine it with a Zonal Reserved Instance or Savings Plans — they automatically apply the discount to matching capacity reservations. Useful for disaster recovery scenarios that need guaranteed available capacity.
Hands-on Exercises
Part 1: AWS CLI and SDK
- Install AWS CLI v2 and run
aws configure - Create 2 profiles (
default,dev) and switch between them - Run
aws sts get-caller-identityto see the account in use - List all EC2 instances across all Regions (
describe-regions+ loop) - Set up IAM Identity Center with
aws configure sso - Try CloudShell in the AWS Console
Part 2: EC2 Basics
- Launch an EC2 t2.micro Amazon Linux 2023 with User Data that installs Apache
- SSH into the instance and check that Apache is running
- Create a custom AMI from this instance
- Stop and Start the instance, observe the Public IP change
- Configure IMDSv2 as required for the instance
- Create a Security Group for a web server (ports 80, 443, 22)
Part 3: EC2 Pricing Models
- Go to AWS Console → EC2 → Reserved Instances → view the RI Marketplace
- Calculate the 3-year total cost of 1 m5.xlarge for each pricing model with the Pricing Calculator
- Launch 1 Spot Instance with max price = the On-Demand price, observe the Spot Price over 24h
- Create a 1-year Compute Savings Plan with a $1/hour commitment (note: just to try it, cancel if not needed)
References
- AWS CLI User Guide
- AWS CLI v2 Installation
- Credentials Provider Chain
- AWS CloudShell
- boto3 Documentation
- AWS CDK Workshop
- Amazon EC2 User Guide
- Instance Types
- AMI Documentation
- Instance Metadata (IMDSv2)
- Placement Groups
- EC2 Pricing
- Reserved Instances
- Savings Plans
- Spot Instances
- Dedicated Hosts