devHọc Dev
Bài học

Tuần 8 - Ngày 1: Monitoring và Logging

Tuần 8 – Ngày 1

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

  • Nắm các thành phần CloudWatch (metrics, logs, alarms, dashboards) và pattern subscription filter
  • Phân biệt CloudTrail (ai làm gì) vs Config (trạng thái cấu hình) vs X-Ray (trace request)
  • Thiết kế centralized logging multi-account ở mức Professional

1. CloudWatch Deep Dive

CLOUDWATCHCOMPONENTSMETRICS:Standard(1-minutefordetailed)Custom(PutMetricDataAPI)High-resolution(1-second)LOGS:LogGroupsLogStreamsLogEventsMetricFiltersSubscriptionFiltersLogInsights(querylanguage)ALARMS:MetricAlarmsCompositeAlarmsActions:SNS,AutoScaling,EC2DASHBOARDS:Cross-account,cross-regionEVENTS(EventBridge):RulesTargets(Lambda,SNS,etc.)

2. CloudWatch Logs Architecture

LOGSDESTINATIONSSources:EC2(CloudWatchAgent)Lambda(automatic)VPCFlowLogsAPIGatewayManymore...Processing:CloudWatchLogsSubscriptionFilterKinesisLambdaOpenSearchFirehoseStreamsServiceS3

3. X-Ray

Distributed Tracing:
- Trace requests across services
- Service map visualization
- Performance bottleneck identification

Components:
- X-Ray SDK (in application)
- X-Ray Daemon (collects and sends traces)
- X-Ray Console (analysis)

Sampling:
- First request each second: traced
- 5% of additional requests: traced
- Custom sampling rules available

4. CloudTrail

CLOUDTRAILEventTypes:ManagementEvents(default)APIcalls(CreateBucket,RunInstances)DataEvents(extracost)S3objectoperations,LambdainvocationsInsightsEventsUnusualactivitydetectionTrailConfigurations:SingleregionorallregionsOrganizationtrailLogtoS3and/orCloudWatchLogsEncryptionwithKMSBestPractice:-Enableinallregions-LogtocentralizedS3bucket-Enablelogfilevalidation

5. AWS Config

Configurationtrackingandcompliance:Rules:AWSManagedRules(200+)CustomRules(Lambda)Examples:-s3-bucket-public-read-prohibited-encrypted-volumes-iam-password-policyConformancePacks:-Pre-builttemplates-PCIDSS,HIPAA,CIS-Custompacks

6. AWS Health (Personal Health Dashboard)

Monitoring không chỉ là metric/log của workload — còn phải biết khi chính AWS có sự cố hoặc lên lịch bảo trì ảnh hưởng tài nguyên của bạn. Đó là việc của AWS Health.

6.1. Hai góc nhìn của AWS Health Dashboard

Service healthYour account health
Tên cũService Health Dashboard (SHD)Personal Health Dashboard (PHD)
Phạm viTrạng thái chung của mọi service/region, public, không cần đăng nhậpSự kiện ảnh hưởng tài nguyên CỦA BẠN (cá nhân hoá theo account)
Nội dungService đang operational/degraded ở region nàoScheduled changes (EC2 instance retirement, maintenance EBS/RDS), service issues đang tác động resource cụ thể
Chi tiếtKhông biết bạn có bị ảnh hưởng hay khôngTimeline sự kiện + danh sách affected resources (instance ID, volume ID...)

Đề thi hỏi "how to know if your resources are affected by an AWS event" → Your account health (PHD), không phải trang status public.

6.2. AWS Health API và organizational view

  • AWS Health API: truy cập programmatic vào các health event — yêu cầu Business hoặc Enterprise Support plan (điểm hay bị gài trong đề).
  • Organizational view: bật ở management account (hoặc delegated administrator) → gom health event của toàn bộ member account trong Organization về một chỗ. Pattern chuẩn cho ops team trung tâm theo dõi sự cố/bảo trì trên hàng trăm account mà không phải đăng nhập từng account.

6.3. Automation với EventBridge

AWS Health phát event vào EventBridge (source aws.health) → rule → target tự động hoá:

AUTO-REMEDIATION:EC2INSTANCERETIREMENTAWSHealthevent:"EC2instancescheduledforretirement"rulematch:EventBridgesource=aws.healthRuleeventTypeCode=AWS_EC2_INSTANCE_RETIREMENT_SCHEDULEDSNSLambdastopstartinstancenotify(EBS-backedchuynopssanghostmiTRƯCdeadlineretirement)

Ví dụ kinh điển hay thi: AWS lên lịch retire host vật lý → event EC2 instance scheduled for retirement xuất hiện trong PHD → EventBridge rule bắt event → Lambda stop rồi start instance (EBS-backed) để nó được đặt lên host mới trước deadline, thay vì chờ AWS cưỡng chế. SNS song song để notify on-call.

6.4. Exam keywords

  • "be notified when AWS schedules maintenance on YOUR resources" → AWS Health (Your account health / PHD) + EventBridge → SNS. Không phải CloudWatch metric — retirement/maintenance không phải là metric của workload.
  • "automate response to instance retirement" → AWS Health event + EventBridge rule + Lambda (stop/start).
  • "aggregate health events across all accounts in the Organization" → AWS Health organizational view (delegated admin, cần Business/Enterprise Support cho Health API).

7. Câu hỏi ôn tập

  1. CloudTrail vs Config — khác nhau cốt lõi và khi nào dùng cả hai?

    Xem đáp án

    CloudTrail trả lời "AI đã gọi API gì, khi nào, từ đâu" (audit trail các API call). Config trả lời "resource đang/từng có cấu hình gì, có compliant không" (configuration timeline + rules). Ví dụ security group bị mở 0.0.0.0/0: Config rule phát hiện trạng thái non-compliant (+ auto-remediation), CloudTrail cho biết ai đã gọi AuthorizeSecurityGroupIngress. Điều tra incident hoàn chỉnh cần cả hai — đề hỏi "who made the change" → CloudTrail; "detect non-compliant configuration + remediate" → Config.

  2. Subscription filter dùng khi nào thay vì export S3?

    Xem đáp án

    Subscription filter: stream log near real-time ra Lambda (xử lý ngay), Kinesis Data Streams (multi-consumer), Firehose (đổ S3/OpenSearch) — dùng cho real-time alerting, centralized logging cross-account (destination ở account log trung tâm). Export task sang S3: batch, trễ tới 12 giờ — chỉ cho archive thủ công. Pattern chuẩn multi-account: mỗi account có subscription filter → Kinesis/Firehose ở log-archive account → S3 + Athena phân tích.

  3. Composite alarm giải quyết vấn đề gì?

    Xem đáp án

    Kết hợp nhiều alarm bằng AND/OR để giảm alarm noise: chỉ báo khi (CPU cao AND latency cao), hoặc suppress alarm con khi có maintenance alarm. Use case Professional: hàng trăm microservices — thay vì on-call nhận 50 alert khi 1 AZ lỗi, composite alarm gom thành 1 alert "AZ degradation". Actions vẫn là SNS/Auto Scaling như metric alarm thường.

  4. CloudTrail organization trail có lợi thế gì so với trail từng account?

    Xem đáp án

    Tạo một lần ở management account (hoặc delegated administrator) → tự động áp cho mọi member account kể cả account mới join, member không tắt được — đảm bảo audit coverage 100% không phụ thuộc từng team. Log đổ về một S3 bucket trung tâm (thường ở log-archive account) với log file validation + KMS. Đây là đáp án chuẩn cho "ensure all accounts in Organization log API activity, prevent tampering".

  5. AWS thông báo một EC2 instance "scheduled for retirement" — làm sao được notify và tự động xử lý trước deadline?

    Xem đáp án

    Sự kiện này xuất hiện trong AWS Health Dashboard – Your account health (Personal Health Dashboard) dưới dạng scheduled change, kèm affected resources — không phải CloudWatch metric nên alarm thường không bắt được. Giải pháp: EventBridge rule match source = aws.health, eventTypeCode = AWS_EC2_INSTANCE_RETIREMENT_SCHEDULED → target SNS (notify ops) + Lambda tự động stop → start instance (EBS-backed) để nó chuyển sang host mới trước deadline. Cần gom event toàn Organization → bật organizational view với delegated administrator (Health API yêu cầu Business/Enterprise Support).

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

  1. Metric filter + alarm: tạo metric filter đếm pattern ERROR trong log group của một Lambda, gắn alarm ngưỡng ≥ 5 lỗi/5 phút gửi SNS email; bơm lỗi thử để verify.

  2. Subscription filter cross-account: tạo CloudWatch Logs destination (Kinesis) ở account B, subscription filter ở account A trỏ sang; verify log event chảy cross-account — đây là xương sống của centralized logging.

  3. Config rule + timeline: bật Config recorder, deploy managed rule encrypted-volumes; tạo EBS volume không mã hoá và xem resource timeline chuyển NON_COMPLIANT.

  4. X-Ray tracing: bật Active tracing trên 1 Lambda sau API Gateway, gọi vài request và đọc service map để tìm bottleneck.


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


Ngày tiếp theo: EventBridge và Automation