devHọc Dev
EN
Bài học

Tuần 1 - Ngày 2: AWS CLI/SDK, EC2 Basics và EC2 Pricing Models

Tuần 1 – Ngày 2

Bài này gộp 3 chủ đề: AWS CLI và SDK, EC2 Basics, EC2 Pricing Models.

Mục tiêu học tập

  • Cài đặt và cấu hình AWS CLI v2
  • Hiểu Credentials Provider Chain
  • Biết dùng Named Profiles, MFA với CLI
  • Phân biệt CLI, SDK, CloudShell, CDK
  • Hiểu EC2 instance lifecycle và các thành phần cơ bản
  • Phân biệt các loại Instance Family (General, Compute, Memory, Storage)
  • Nắm AMI, User Data, Instance Metadata, Key Pair
  • Hiểu Security Group cho EC2
  • Hiểu chi tiết 5 pricing models EC2
  • Biết khi nào dùng RI vs Savings Plans vs Spot
  • Hiểu Dedicated Host vs Dedicated Instance
  • Áp dụng pricing model cho từng workload pattern

Phần 1: AWS CLI và SDK

1. AWS CLI (Command Line Interface)

Định nghĩa

AWS CLI là tool dòng lệnh để tương tác với AWS services qua API.

Phiên bản

  • AWS CLI v2 (recommended) — bundled Python, faster, better UX
  • AWS CLI v1 — legacy, đã sắp deprecated

Cài đặt

# 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: tải MSI installer từ https://aws.amazon.com/cli/

# Verify
aws --version
# Output: aws-cli/2.x.x Python/3.x.x ...

2. Configure CLI

Cách 1: aws configure (đơn giản nhất)

$ 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

→ Tạo 2 files:

  • ~/.aws/credentials (chứa keys)
  • ~/.aws/config (chứa region, output format)

Cấu trúc files

# ~/.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

Dùng 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

AWS CLI/SDK tìm credentials theo thứ tự ưu tiên sau (dừng ở cái đầu tiên tìm thấy):

1.Command-lineoptions└──--access-key,--secret-key,--session-token2.EnvironmentVariables├──AWS_ACCESS_KEY_ID├──AWS_SECRET_ACCESS_KEY└──AWS_SESSION_TOKEN3.IAMIdentityCenter(têncũ:AWSSSO)└──awsconfiguresso4.WebIdentityToken(Cognito,OIDC)5.Sharedcredentialsfile└──~/.aws/credentials(profilemặcđịnhhoặcAWS_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) hoặc named profile
  • EC2: IAM Role attach vào instance (không hard-code key)
  • ECS/Fargate: Task Role
  • Lambda: Execution Role
  • CI/CD: OIDC federation (GitHub Actions, GitLab) thay vì 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 và Query

# --filters: server-side filter (tiết kiệm bandwidth)
aws ec2 describe-instances \
  --filters "Name=instance-state-name,Values=running"

# --query: client-side JMESPath (filter sau khi nhận response)
aws ec2 describe-instances \
  --query 'Reservations[*].Instances[*].[InstanceId,InstanceType,State.Name]'

# Kết hợp
aws ec2 describe-instances \
  --filters "Name=tag:Environment,Values=production" \
  --query 'Reservations[*].Instances[*].InstanceId' \
  --output text

5. MFA với CLI

Khi IAM user yêu cầu MFA, CLI cần token tạm thời:

# Lấy temporary credentials với 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": "..."
#   }
# }

Hoặc cấu hình profile auto-prompt 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
# CLI sẽ prompt: Enter MFA code:

6. AWS CloudShell

Định nghĩa

CloudShell là browser-based shell trong AWS Console, đã preinstall AWS CLI, Python, Node.js, Git.

Đặc điểm

  • Miễn phí (không tốn EC2)
  • 1 GB persistent storage mỗi Region (lưu home directory)
  • Authenticated tự động bằng identity console hiện tại
  • Available ở 1 số Region (us-east-1, eu-west-1, ap-southeast-1...)
  • Idle timeout: 20-30 phút

Use case

  • Run AWS CLI command nhanh mà không cần setup local
  • Học AWS CLI trong môi trường an toàn
  • Quick scripts mà không cần local environment

7. AWS SDK

Định nghĩa

SDK (Software Development Kit) là thư viện cho phép app gọi AWS APIs từ code.

Các SDK chính

Ngôn ngữPackage
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...Có

Ví dụ Python boto3

import boto3

# Tạo S3 client (auto picks credentials từ 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) — Khái niệm

Định nghĩa

CDK cho phép define infrastructure bằng code (TypeScript, Python, Java, C#, Go) thay vì YAML/JSON CloudFormation.

Workflow

CDK code (TypeScript)
       │
       ▼
   cdk synth  →  CloudFormation template (JSON/YAML)
       │
       ▼
   cdk deploy →  AWS CloudFormation creates resources

Ưu điểm so với CloudFormation thuần

  • Type safety, autocomplete
  • Reusable constructs (L1/L2/L3)
  • Loops, conditionals (logic của ngôn ngữ chính)
  • Test với unit test framework

9. So sánh các tools

ToolKhi nào dùng
AWS ConsoleExplore service, click nhanh
AWS CLIScript, automation, CI/CD
AWS SDKBuild application
AWS CloudShellCLI without local setup
CloudFormationIaC declarative (JSON/YAML)
AWS CDKIaC programmatic (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" cho 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

Phần 2: EC2 Basics

1. Tổng quan EC2

EC2 (Elastic Compute Cloud) là service IaaS cung cấp virtual servers (instances) on-demand.

Lý do dùng EC2

  • Toàn quyền kiểm soát OS, network, storage
  • Đa dạng instance types (CPU, RAM, GPU, storage)
  • Pay per second (Linux) hoặc per hour (Windows)
  • Scale lên/xuống nhanh chóng

2. Instance Lifecycle

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

So sánh các trạng thái

Trạng tháiCompute chargeEBS chargePublic IP
runningYesYesYes (nếu assigned)
stoppedNoYesMất Public IP (Elastic IP giữ lại)
stopping (hibernate)NoYes—
terminatedNoVolume tự xóa (nếu DeleteOnTermination=true)Mất hết
rebootTính phí bình thường—Giữ Public IP, IP private, EBS

Stop vs Terminate

  • Stop: Lưu state, có thể start lại. Instance ID giữ nguyên. EBS root vẫn còn.
  • Terminate: Xóa instance vĩnh viễn. Mặc định EBS root cũng bị xóa.

Hibernate (đặc biệt)

  • Lưu RAM vào EBS root, restart giữ nguyên state RAM
  • Yêu cầu: EBS root encrypted và đủ chỗ chứa RAM; instance RAM < 150 GB (giới hạn là RAM, không phải size EBS root); instance family support, OS support
  • Use case: Resume nhanh app với warm cache

3. Instance Families

Tổng quan naming: m5.xlarge

m5.xlarge│││││└─Size(nano/micro/small/medium/large/xlarge/2xlarge...)│└──────────────────Generation(caohơn=mớihơn)└──────────────────────────────Family

Các family chính

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
  • Rẻ hơn 20% vs x86, tiết kiệm điện
  • Cần ứng dụng compatible ARM64

Burstable (T family) đặc biệt

  • Tích lũy CPU credits khi idle
  • Tiêu credits khi burst lên 100% CPU
  • 2 chế độ:
    • Standard: Khi hết credits, performance giảm xuống baseline
    • Unlimited (default cho t3/t4g): Vượt baseline phải trả thêm phí

4. AMI (Amazon Machine Image)

Định nghĩa

AMI là template chứa OS, application, configuration để launch EC2.

4 nguồn AMI

LoạiMô tả
Quick StartAWS official: Amazon Linux 2023, Ubuntu, Windows Server, RHEL
AWS MarketplaceThird-party: Bitnami, vendors (có thể trả phí cho software)
Community AMIPublic AMIs từ user khác (cẩn thận về security)
My AMIsAMIs do bạn tạo (custom golden image)

Tạo Custom AMI

  1. Launch EC2 từ AMI base
  2. Cài đặt, cấu hình
  3. Console: Actions → Image → Create Image
  4. AMI có thể share cross-account hoặc public

EBS-backed vs Instance Store-backed AMI

AMI typeBoot timePersistenceStop possible
EBS-backedNhanhPersistent (EBS)Có thể stop
Instance Store-backedChậm hơnMất khi terminateKhông thể stop, chỉ terminate

Hầu hết AMIs hiện đại là EBS-backed.

Region của AMI

  • AMI là regional — chỉ tồn tại ở Region tạo
  • Cross-Region: Copy AMI sang Region khác (mất phí copy)

5. User Data

Định nghĩa

User Data là script chạy lần đầu khi EC2 boot, dùng để bootstrap instance.

Use cases

  • Cài đặt packages (Apache, Node.js)
  • Pull code từ Git
  • Configure CloudWatch agent
  • Join domain Active Directory

Ví dụ Linux bash script

#!/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

Đặc điểm

  • Chạy với root privileges
  • Chỉ chạy 1 lần khi launch (mặc định)
  • Log ở /var/log/cloud-init-output.log
  • Max size: 16 KB (base64-encoded)
  • Có thể edit khi instance stopped

6. Instance Metadata Service (IMDS)

Định nghĩa

Service nội bộ EC2 cung cấp metadata về instance qua endpoint http://169.254.169.254/.

Ví dụ

# Lấy instance ID
curl http://169.254.169.254/latest/meta-data/instance-id
# Output: i-0123456789abcdef0

# Lấy public IP
curl http://169.254.169.254/latest/meta-data/public-ipv4

# Lấy IAM role credentials
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/MyRole

IMDSv1 vs IMDSv2

FeatureIMDSv1IMDSv2
AuthKhôngSession token (PUT request)
VulnerabilitySSRF attacksBảo vệ chống SSRF
StatusLegacyMặc định và bắt buộc khuyến nghị

IMDSv2 workflow

# 1. Lấy 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. Gọi metadata với 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) ở instance launch
  • Disable IMDS hoàn toàn nếu không cần

7. Key Pair (SSH)

Định nghĩa

Key Pair dùng để SSH (Linux) hoặc RDP (Windows) vào EC2.

Các loại

  • RSA (legacy)
  • ED25519 (modern, recommended)

Workflow

  1. Tạo key pair trong AWS Console hoặc import public key
  2. Download .pem file (chỉ download được 1 lần)
  3. chmod 400 my-key.pem
  4. SSH: ssh -i my-key.pem ec2-user@<public-ip>

Mất key pair?

  • Không thể recover từ AWS
  • Workarounds:
    • Tạo AMI mới với key khác
    • Detach root volume, mount sang instance khác, edit ~/.ssh/authorized_keys
    • Dùng EC2 Instance Connect hoặc Systems Manager Session Manager

EC2 Instance Connect

  • Browser-based SSH từ AWS Console
  • Tạm thời push public key vào instance qua API
  • Không cần .pem file local

8. Security Group

Định nghĩa

Security Group là virtual firewall ở instance level (gắn vào ENI).

Đặc điểm

  • Stateful: response traffic tự động được allow
  • Allow rules only (không có Deny rule)
  • Mặc định: deny all inbound, allow all outbound
  • Có thể tham chiếu SG khác làm source/destination
  • Tối đa 5 SG/ENI, 60 rules/SG inbound + 60 outbound

Ví dụ SG cho web server

Inboundrules:─────────────────────────────────────────TypeProtocolPortSourceHTTPTCP800.0.0.0/0(chophépwebpublic)HTTPSTCP4430.0.0.0/0SSHTCP2210.0.0.0/16(chỉtừVPC)Outboundrules:─────────────────────────────────────────AlltrafficAllAll0.0.0.0/0

So sánh với NACL (sẽ học chi tiết ở Tuần 2 Ngày 1, Phần 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 hỗ trợ resource tags (tối đa 50 tags/resource):

  • Name=WebServer-Prod
  • Environment=production
  • Owner=alice@company.com
  • CostCenter=CC-1234

Tags dùng cho:

  • Cost allocation
  • ABAC (attribute-based access control)
  • Auto Scaling filtering
  • AWS Backup selection

Phần 3: EC2 Pricing Models

1. Tổng quan 5 Pricing Models

ModelDiscountCommitmentHoàn lạiUse case
On-Demand0%Không—Test, unpredictable, short-term
Reserved Instance (RI)Lên đến 72%1y / 3yMarketplace bán lại đượcSteady workload
Savings Plans (SP)Lên đến 72%1y / 3yKhông hoàn lạiFlexible commitment
Spot InstanceLên đến 90%KhôngEC2 có thể bị reclaimFault-tolerant, batch
Dedicated Host—On-demand or RI—License BYOL, compliance

2. On-Demand

Đặc điểm

  • Trả theo giây (Linux, min 60s) hoặc giờ (Windows, RHEL, SLES)
  • Không commitment
  • Đắt nhất nhưng linh hoạt nhất

Use case

  • Test/development ngắn hạn
  • Workload không dự đoán được
  • Migration phase đầu (chưa biết exact requirement)
  • Đỉnh tải tạm thời (kèm RI cho baseline)

3. Reserved Instance (RI)

Term

  • 1 năm hoặc 3 năm
  • 3 năm tiết kiệm hơn 1 năm

Payment options

  • All Upfront (AURI): Trả hết → discount lớn nhất
  • Partial Upfront (PURI): Trả 1 phần → discount vừa
  • No Upfront (NURI): Trả hàng tháng → discount thấp hơn

Offering Class

ClassĐổi instance familyĐổi OS, tenancyResell on Marketplace
Standard RIKhôngKhôngCó
Convertible RICó (cùng giá trị trở lên)CóKhông

Scope

  • Regional RI (mặc định): Áp dụng cho any AZ trong Region, không reserve capacity
  • Zonal RI: Áp dụng 1 AZ cụ thể, reserve capacity (đảm bảo có instance khi cần)

Use case

  • Workload chạy 24/7 ổn định trong > 1 năm
  • Database production
  • Web servers ổn định (cùng baseline + ASG cho peak)

Reserved Instance Marketplace

  • Bán RI Standard không còn cần
  • Buyer có thể mua RI < 1 năm remaining từ Marketplace

4. Savings Plans (SP)

Định nghĩa

Savings Plans = commit $X/hour trong 1 hoặc 3 năm, nhận discount trên usage tương ứng.

3 loại SP

TypeÁp dụng choFlexibilityDiscount
Compute Savings PlansEC2 (mọi family, Region), Fargate, LambdaCao nhấtUp to 66%
EC2 Instance Savings PlansEC2 1 family + 1 RegionĐổi size/OS trong familyUp to 72%
SageMaker Savings PlansSageMaker—Up to 64%

So sánh 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 cho phép đổiCao (Compute SP đổi family, region)
ResellStandard RI bán đượcKhông bán được

Khuyến nghị: Compute Savings Plans cho EC2 + serverless workload.

5. Spot Instances

Định nghĩa

Spot = mua spare EC2 capacity với discount lên đến 90% so với On-Demand, nhưng AWS có thể reclaim với 2-min warning.

Spot Price

  • Giá thay đổi theo cung-cầu
  • Bạn set maximum price (tự bid)
  • Nếu Spot Price ≤ max price → instance chạy
  • Nếu Spot Price > max price → instance bị terminate

Spot Instance Interruption Behavior

3 options khi bị reclaim:

  • Terminate (mặc định)
  • Stop (giữ EBS)
  • Hibernate (lưu RAM)

Spot Fleet vs Spot Request

Spot RequestSpot Fleet
Số instance1Multiple, mix On-Demand + Spot
Allocation strategy—lowest-price, diversified, capacity-optimized

Allocation Strategy (cho Spot Fleet & ASG mixed)

  • lowestPrice: Pool với giá thấp nhất
  • diversified: Phân tán qua nhiều pool
  • capacityOptimized: Pool ít bị interrupt nhất (recommended)
  • priceCapacityOptimized: Cân bằng price + capacity

Use case Spot

  • Batch processing
  • Big data (EMR, Spark)
  • CI/CD workers
  • Containerized stateless workload (ECS/EKS)
  • Image/video rendering
  • KHÔNG dùng cho: Database, single-instance critical apps

Spot Block (đã deprecated)

  • Trước đây: Spot reserve 1-6 hours không bị reclaim
  • AWS đã ngừng Spot Block từ 2021 cho new customers. Hiện chỉ còn Spot Request thông thường.

6. Dedicated Host

Định nghĩa

Dedicated Host = physical server vật lý dành riêng cho 1 account, có visibility xuống socket/core level.

Đặc điểm

  • Bạn trả tiền theo host (not theo instance)
  • Visibility vào CPU socket, physical cores
  • License BYOL (Bring Your Own License) cho Windows Server, SQL Server, Oracle
  • Compliance (regulatory requires dedicated hardware)
  • Hỗ trợ Host Affinity: instance luôn launch trên cùng host khi stop/start

Pricing

  • On-Demand Dedicated Host: $/hour
  • Reserved Dedicated Host: 1y/3y term, discount lên đến ~70%

7. Dedicated Instance

Định nghĩa

Dedicated Instance = EC2 instance chạy trên hardware dedicated cho 1 account, nhưng bạn không có visibility xuống socket.

So sánh Dedicated Host vs Dedicated Instance

Dedicated HostDedicated Instance
PricingPer hostPer instance
Visibility hardwareCó (socket, core)Không
BYOLCóHạn chế
Same host across stop/startCó (Host Affinity)Không guaranteed
Use caseStrict compliance, BYOLCompliance vừa phải

8. Capacity Reservations

Định nghĩa

On-Demand Capacity Reservation (ODCR) = reserve EC2 capacity ở 1 AZ cụ thể, không discount giá, chỉ đảm bảo có capacity khi cần.

Use case

  • Đảm bảo capacity cho event quan trọng (Black Friday)
  • DR scenarios (đảm bảo có capacity để failover)
  • Combination: ODCR + Savings Plans = capacity + discount

So sánh

Zonal RIOn-Demand Capacity Reservation
DiscountCóKhông
Capacity guaranteeCóCó
Commitment1y/3yKhông (có thể cancel anytime)

9. So sánh tổng hợp — Chọn pricing nào?

Workloadpattern→Recommendedpricing────────────────────────────────────────────────────────────Steady-state,24/7,>1year→ReservedInstance3yAURISteady+biếtfamily/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 hoặc Compute SP
Variable workload           → On-Demand
Burst/batch                 → Spot

Ví dụ web app:

  • 10 instances baseline → 10 RI 3-year (~72% off)
  • 5 instances peak hours → On-Demand
  • Background processing → Spot

10. Bài toán so sánh chi phí

Scenario: EC2 t3.medium chạy 24/7, 3 năm, us-east-1.

PricingGiá $/hourTổng 3 nămTiết kiệm
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% (nhưng có thể bị reclaim)

Giá thay đổi theo region và thời điểm — đây chỉ là minh họa.


Câu hỏi ôn tập

  1. EC2 instance cần access S3 — nên cấu hình credentials theo cách nào?

    Xem đáp án

    Attach IAM Role (Instance Profile) vào EC2 instance. SDK/CLI trên instance sẽ tự động lấy temporary credentials từ Instance Metadata Service (IMDSv2) tại http://169.254.169.254. Không cần cấu hình gì thêm trong code — credentials được rotate tự động mỗi giờ. Tuyệt đối không hard-code Access Key ID/Secret trong code, config file, hay environment variable trên server.

  2. Liệt kê thứ tự ưu tiên trong Credentials Provider Chain (top 3)?

    Xem đáp án

    (1) Command-line options (--access-key, --secret-key) — cao nhất. (2) Environment variables (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN). (3) IAM Identity Center session (aws configure sso; tên cũ AWS SSO). Tiếp theo: Web Identity Token, shared credentials file (~/.aws/credentials), config file, container credentials, EC2 Instance Profile. Chain dừng tại entry đầu tiên tìm thấy.

  3. AWS CloudShell có tính phí không?

    Xem đáp án

    Miễn phí. CloudShell không tính phí compute riêng. Bạn được 1 GB persistent storage miễn phí mỗi Region (home directory). Chỉ tính phí nếu CloudShell thực hiện AWS API calls tạo resources (ví dụ launch EC2) — nhưng bản thân shell không có phí. Tự động authenticated bằng identity đang đăng nhập Console.

  4. Khác biệt giữa --filters và --query trong AWS CLI?

    Xem đáp án

    --filters là server-side filtering — AWS xử lý filter trước khi trả response, tiết kiệm bandwidth và thời gian với dataset lớn. --query là client-side filtering (JMESPath) — AWS trả toàn bộ response, CLI filter local. Kết hợp cả hai: --filters giảm data từ server, --query extract fields cần thiết từ response. --filters chỉ hoạt động với các fields AWS hỗ trợ filter; --query linh hoạt hơn với bất kỳ field nào trong JSON.

  5. CDK khác CloudFormation ở điểm gì?

    Xem đáp án

    CDK cho phép define infrastructure bằng ngôn ngữ lập trình (TypeScript, Python, Java, Go...) với type safety, autocomplete, loops, conditionals, và unit tests. CDK compile ra CloudFormation template (cdk synth) rồi deploy qua CloudFormation. CloudFormation thuần dùng YAML/JSON declarative — verbose hơn và không có logic programming. CDK có L2/L3 constructs (high-level abstractions) giúp viết ít code hơn cho patterns phổ biến.

  6. Sự khác biệt giữa Stop và Terminate của EC2?

    Xem đáp án

    Stop: instance tắt, vẫn tồn tại, có thể start lại. EBS root volume giữ nguyên. Public IP mất (nhưng Elastic IP giữ). Không tính compute charge khi stopped, vẫn tính EBS charge. Terminate: instance bị xoá vĩnh viễn. EBS root volume bị xoá (nếu DeleteOnTermination=true). Không thể undo. Stop dùng để tạm dừng; Terminate để xoá hẳn.

  7. T-family đặc biệt ở điểm gì so với M-family?

    Xem đáp án

    T-family (t3, t4g) dùng burstable CPU model: instance tích lũy "CPU credits" khi idle, dùng credits để burst lên CPU cao khi cần. Phù hợp cho workload không đều (web dev server, small DB). M-family (m6i, m7g) cung cấp dedicated, consistent CPU — không có credit mechanism. M-family cho workload steady như production web server cần CPU ổn định.

  8. AMI EBS-backed có ưu điểm gì so với Instance Store-backed?

    Xem đáp án

    EBS-backed AMI: có thể Stop instance (data persist trên EBS), khởi động nhanh hơn (boot từ EBS snapshot), dễ tạo AMI snapshot, root volume có thể detach. Instance Store-backed: data mất khi stop/terminate (ephemeral) — chỉ còn trong lúc running. EBS-backed là lựa chọn mặc định và phù hợp cho hầu hết use cases.

  9. IMDSv2 khác IMDSv1 ở điểm gì về bảo mật?

    Xem đáp án

    IMDSv1 cho phép gọi metadata trực tiếp không cần authentication — dễ bị SSRF (Server-Side Request Forgery) attack: attacker exploit SSRF để lấy IAM credentials từ metadata endpoint. IMDSv2 yêu cầu session token (lấy qua PUT request trước) — SSRF thông thường không thể làm PUT request, ngăn chặn SSRF credentials theft. Khuyến nghị enforce IMDSv2 (Required) cho tất cả instances.

  10. Khi nào dùng Cluster vs Spread Placement Group?

Xem đáp án

Cluster Placement Group: tất cả instances trong cùng AZ, cùng rack hardware, kết nối 10 Gbps+ network. Dùng cho HPC, big data, low-latency applications cần network bandwidth cao (Hadoop, ML training). Rủi ro: một lần hardware failure có thể ảnh hưởng nhiều instances. Spread Placement Group: mỗi instance trên hardware riêng biệt, có thể across AZs. Dùng cho critical applications cần max HA — tối đa 7 instances/AZ/group.

  1. RI Standard và Convertible khác nhau ở điểm gì?
Xem đáp án

Standard RI: discount cao hơn (lên đến 72%), không thể đổi instance family/OS/tenancy trong thời hạn, có thể bán lại trên RI Marketplace. Convertible RI: discount thấp hơn (~54%), có thể exchange sang RI khác cùng hoặc cao hơn giá trị (đổi instance family, OS, tenancy — không đổi được Region và term, RI gắn với Region), không bán lại được. Chọn Standard khi workload ổn định rõ ràng; Convertible khi cần flexibility.

  1. Khi nào dùng Compute Savings Plans thay vì EC2 Instance Savings Plans?
Xem đáp án

Compute Savings Plans áp dụng cho EC2 (bất kỳ instance family, Region, OS, tenancy), Lambda, và Fargate — flexible nhất nhưng discount thấp hơn (~66%). EC2 Instance Savings Plans chỉ áp dụng cho một instance family trong một Region cụ thể — discount cao hơn (~72%) nhưng ít flexible. Chọn Compute SP khi có workload Lambda/Fargate đáng kể hoặc cần thay đổi instance family; EC2 Instance SP khi workload EC2 ổn định và biết rõ instance family.

  1. Spot Instance bị AWS reclaim sau bao lâu warning?
Xem đáp án

2 phút (120 giây) warning trước khi AWS reclaim. Spot Instance gửi interruption notice qua Instance Metadata và EventBridge. Ứng dụng phải handle gracefully trong 2 phút này: checkpoint work, drain connections, save state. Spot phù hợp cho batch jobs, data processing, stateless workloads — không phù hợp cho databases hay stateful apps không chịu được interruption.

  1. Use case nào BẮT BUỘC dùng Dedicated Host thay vì Dedicated Instance?
Xem đáp án

BYOL (Bring Your Own License) cho phần mềm tính phí theo physical server hoặc per-socket/per-core — ví dụ Windows Server, SQL Server, Oracle Database với license models dựa trên physical host specs. Dedicated Host cung cấp visibility về số cores và socket trên physical server cụ thể — cần thiết để comply với license terms. Dedicated Instance chỉ đảm bảo isolated hardware nhưng không cung cấp host-level visibility.

  1. On-Demand Capacity Reservation có cho discount giá không?
Xem đáp án

Không. On-Demand Capacity Reservation đảm bảo reserved capacity trong một AZ cụ thể nhưng tính phí On-Demand rate — không có discount. Để vừa có capacity reservation vừa có discount, kết hợp với Zonal Reserved Instance hoặc Savings Plans — chúng tự động áp dụng discount lên capacity reservation matching. Hữu ích cho disaster recovery scenarios cần đảm bảo capacity sẵn sàng.

Bài tập thực hành

Phần 1: AWS CLI và SDK

  • Cài AWS CLI v2 và chạy aws configure
  • Tạo 2 profiles (default, dev) và chuyển đổi giữa chúng
  • Chạy aws sts get-caller-identity xem account đang dùng
  • List tất cả EC2 instances trong tất cả Region (describe-regions + loop)
  • Setup IAM Identity Center với aws configure sso
  • Thử CloudShell trong AWS Console

Phần 2: EC2 Basics

  • Launch EC2 t2.micro Amazon Linux 2023 với User Data cài Apache
  • SSH vào instance, kiểm tra Apache đang chạy
  • Tạo custom AMI từ instance này
  • Stop và Start instance, quan sát thay đổi Public IP
  • Configure IMDSv2 required cho instance
  • Tạo Security Group cho web server (port 80, 443, 22)

Phần 3: EC2 Pricing Models

  • Vào AWS Console → EC2 → Reserved Instances → xem RI Marketplace
  • Tính tổng chi phí 3 năm cho 1 m5.xlarge với từng pricing model qua Pricing Calculator
  • Launch 1 Spot Instance với max price = giá On-Demand, observe Spot Price trong 24h
  • Tạo Compute Savings Plans 1-year, $1/hour commitment (lưu ý: thử thôi, cancel nếu không cần)

Tài liệu tham khảo


Bài tiếp theo →