</>Học Dev
Bài học

Tuần 2 - Ngày 1: EC2 Basics

Tuần 2 – Ngày 1

Tuần 2 - Ngày 1: EC2 Basics

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

  • 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

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

launchstoppendingrunningstoppingrebootstartrunningstoppedterminateterminated

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ườngGiữ 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, < 150 GB, instance family support, OS support
  • Use case: Resume nhanh app với warm cache

3. Instance Families

Tổng quan naming: m5.xlarge

m5.xlargeSize(nano/micro/small/medium/large/xlarge/2xlarge...)Generation(caohơn=mihơ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 2, 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(chtVPC)Outboundrules:AlltrafficAllAll0.0.0.0/0

So sánh với NACL (sẽ học chi tiết Tuần 4)

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

9. Placement Groups

3 strategies

CLUSTERSPREADPARTITIONSingleAZMulti-AZMulti-partitionSamerackDifferentHWEachAZ[I][I][I][I][I][I][I]P1:[I][I][I]LowlatencyMax7/AZP2:[I][I][I]NosharedHWHDFS,CassandraHPC,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

Câu hỏi ôn tập

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

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

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

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

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

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

  • Launch EC2 t2.micro Amazon Linux 2 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)

Tài liệu tham khảo chính thức


Tiếp theo: EC2 Pricing Models