devHọc Dev

Week 1 - Day 2: AWS CLI/SDK, EC2 Basics and EC2 Pricing Models

Week 1 – Day 2

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):

1.Command-lineoptions└──--access-key,--secret-key,--session-token2.EnvironmentVariables├──AWS_ACCESS_KEY_ID├──AWS_SECRET_ACCESS_KEY└──AWS_SESSION_TOKEN3.IAMIdentityCenter(formerlyAWSSSO)└──awsconfiguresso4.WebIdentityToken(Cognito,OIDC)5.Sharedcredentialsfile└──~/.aws/credentials(defaultprofileorAWS_PROFILE)6.Sharedconfigfile└──~/.aws/config7.Containercredentials(ECS/Fargate)└──AWS_CONTAINER_CREDENTIALS_RELATIVE_URI8.EC2InstanceProfile(IMDSv2)└──http://169.254.169.254/latest/meta-data/iam/security-credentials/<role>

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

LanguagePackage
Pythonboto3
JavaScript/Node.js@aws-sdk/client-* (v3 modular)
Javaaws-sdk-java-v2
.NETAWSSDK.* (NuGet)
Gogithub.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

ToolWhen to use
AWS ConsoleExplore services, quick clicks
AWS CLIScripts, automation, CI/CD
AWS SDKBuild applications
AWS CloudShellCLI without local setup
CloudFormationDeclarative IaC (JSON/YAML)
AWS CDKProgrammatic IaC (code)
TerraformMulti-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

┌──────────┐launch┌──────────┐stop┌──────────┐│pending│───────►│running│──────►│stopping│└──────────┘└──────────┘└──────────┘│▲│reboot││start│▼│▼┌──────────┐┌──────────┐│running││stopped│└──────────┘└──────────┘│terminate│▼┌──────────┐│terminated│└──────────┘

Comparing the states

StateCompute chargeEBS chargePublic IP
runningYesYesYes (if assigned)
stoppedNoYesPublic IP is lost (Elastic IP is kept)
stopping (hibernate)NoYes—
terminatedNoVolume deleted automatically (if DeleteOnTermination=true)All lost
rebootCharged 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

m5.xlarge│││││└─Size(nano/micro/small/medium/large/xlarge/2xlarge...)│└──────────────────Generation(higher=newer)└──────────────────────────────Family

Main families

FamilyTypeUse caseExamples
TBurstableWeb servers, dev, low traffict3, t3a, t4g
MGeneral purposeBalanced CPU/RAMm5, m6i, m7g
CCompute-optimizedBatch, gaming, scientificc5, c6i, c7g
RMemory-optimizedIn-memory DB, real-time analyticsr5, r6i, x2idn
XHigh memorySAP HANA, large in-memory DBx1, x2
IStorage (NVMe SSD)NoSQL, data warehousei3, i4i
DStorage (HDD)Distributed file systems, Hadoopd2, d3
G/PGPUMachine learning, graphicsg4dn, p4d
FFPGAGenomics, financial analyticsf1
InfAWS InferentiaML inferenceinf1, inf2
TrnAWS TrainiumML trainingtrn1

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

TypeDescription
Quick StartAWS official: Amazon Linux 2023, Ubuntu, Windows Server, RHEL
AWS MarketplaceThird-party: Bitnami, vendors (software may be paid)
Community AMIPublic AMIs from other users (be careful about security)
My AMIsAMIs you create (custom golden image)

Creating a Custom AMI

  1. Launch EC2 from a base AMI
  2. Install and configure
  3. Console: Actions → Image → Create Image
  4. The AMI can be shared cross-account or made public

EBS-backed vs Instance Store-backed AMI

AMI typeBoot timePersistenceStop possible
EBS-backedFastPersistent (EBS)Can be stopped
Instance Store-backedSlowerLost on terminateCannot 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

FeatureIMDSv1IMDSv2
AuthNoneSession token (PUT request)
VulnerabilitySSRF attacksProtects against SSRF
StatusLegacyDefault 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

  1. Create a key pair in the AWS Console or import a public key
  2. Download the .pem file (you can download it only once)
  3. chmod 400 my-key.pem
  4. 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 .pem file 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

Inboundrules:─────────────────────────────────────────TypeProtocolPortSourceHTTPTCP800.0.0.0/0(allowpublicweb)HTTPSTCP4430.0.0.0/0SSHTCP2210.0.0.0/16(onlyfromtheVPC)Outboundrules:─────────────────────────────────────────AlltrafficAllAll0.0.0.0/0

Comparison with NACLs (covered in detail in Week 2 Day 1, Part 3)

Security GroupNACL
ScopeInstance (ENI)Subnet
StateStatefulStateless
RulesAllow onlyAllow + Deny

9. Placement Groups

3 strategies

CLUSTERSPREADPARTITION┌─────────────────┐┌─────────────────┐┌─────────────────┐│SingleAZ││Multi-AZ││Multi-partition││Samerack││DifferentHW││EachAZ││││││││[I][I][I][I]││[I][I][I]││P1:[I][I][I]││Lowlatency││Max7/AZ││P2:[I][I][I]││││NosharedHW││HDFS,Cassandra│└─────────────────┘└─────────────────┘└─────────────────┘HPC,lowlatencyCritical,isolationBigdata
StrategyUse caseLimit
ClusterHPC, low-latency between instances1 AZ
SpreadCritical apps, isolationMax 7 instances/AZ
PartitionDistributed systems (HDFS, Kafka)Up to 7 partitions/AZ

10. Tags

EC2 supports resource tags (up to 50 tags/resource):

  • Name=WebServer-Prod
  • Environment=production
  • Owner=alice@company.com
  • CostCenter=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

ModelDiscountCommitmentRefund/exitUse case
On-Demand0%None—Test, unpredictable, short-term
Reserved Instance (RI)Up to 72%1y / 3yCan be resold on the MarketplaceSteady workload
Savings Plans (SP)Up to 72%1y / 3yNon-refundableFlexible commitment
Spot InstanceUp to 90%NoneEC2 can be reclaimedFault-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

ClassChange instance familyChange OS, tenancyResell on Marketplace
Standard RINoNoYes
Convertible RIYes (equal or greater value)YesNo

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

TypeApplies toFlexibilityDiscount
Compute Savings PlansEC2 (any family, Region), Fargate, LambdaHighestUp to 66%
EC2 Instance Savings PlansEC2 1 family + 1 RegionChange size/OS within the familyUp to 72%
SageMaker Savings PlansSageMaker—Up to 64%

RI vs Savings Plans

Reserved InstanceSavings Plans
CommitmentInstance attributes (type, OS, region)$/hour spend
Apply toEC2, RDS, ElastiCache, OpenSearch, RedshiftEC2 + Fargate + Lambda (Compute SP)
FlexibilityConvertible RI allows changesHigh (Compute SP changes family, region)
ResellStandard RI can be resoldCannot 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 RequestSpot Fleet
Number of instances1Multiple, 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 HostDedicated Instance
PricingPer hostPer instance
Hardware visibilityYes (socket, core)No
BYOLYesLimited
Same host across stop/startYes (Host Affinity)Not guaranteed
Use caseStrict compliance, BYOLModerate 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 RIOn-Demand Capacity Reservation
DiscountYesNo
Capacity guaranteeYesYes
Commitment1y/3yNone (can cancel anytime)

9. Overall comparison — Which pricing to choose?

Workloadpattern→Recommendedpricing────────────────────────────────────────────────────────────Steady-state,24/7,>1year→ReservedInstance3yAURISteady+knownfamily/region→EC2InstanceSavingsPlansFlexibleworkload,multi-service→ComputeSavingsPlansUnpredictable,shortbursts→On-DemandBatch,fault-tolerant→SpotInstancesNeedcapacityguarantee→ODCR+SavingsPlansBYOLWindows/Oracle→DedicatedHostCompliancededicatedHW→DedicatedHost/Instance

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.

PricingPrice $/hour3-year totalSavings
On-Demand$0.0416~$1,0930%
RI 1-year NURI$0.029~$76230%
RI 3-year AURI$0.0134~$35268%
Compute SP 3-year AURI$0.014~$36866%
Spot (avg)$0.013~$34169% (but can be reclaimed)

Prices vary by region and over time — this is only an illustration.


Review Questions

  1. 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.

  2. 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.

  3. 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.

  4. What is the difference between --filters and --query in the AWS CLI?

    Show answer

    --filters is server-side filtering — AWS applies the filter before returning the response, saving bandwidth and time with large datasets. --query is client-side filtering (JMESPath) — AWS returns the full response and the CLI filters locally. Combine both: --filters reduces data from the server, --query extracts the fields you need from the response. --filters only works with fields AWS supports for filtering; --query is more flexible with any field in the JSON.

  5. 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.

  6. 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.

  7. 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.

  8. 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.

  9. 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.

  10. 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.

  1. 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.

  1. 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.

  1. 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.

  1. 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.

  1. 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-identity to 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


Next lesson →