devHọc Dev
EN
Bài học

Tuần 4 - Ngày 3: Cost Management và Optimization

Tuần 4 – Ngày 3

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

  • Dùng đúng tool cho từng việc: Cost Explorer (phân tích), Budgets (kiểm soát), CUR (chi tiết), Trusted Advisor/Compute Optimizer (khuyến nghị)
  • So sánh RI vs Savings Plans vs Spot theo scenario Professional
  • Thiết kế cost governance multi-account (tags, SCPs, budget actions)

Tổng quan AWS Cost Management

┌─────────────────────────────────────────────────────────────┐│AWSCOSTMANAGEMENTTOOLS││││Planning&Budgeting:││├──AWSPricingCalculator││├──AWSBudgets││└──CostAllocationTags││││Monitoring&Analysis:││├──AWSCostExplorer││├──AWSCostandUsageReport(CUR)││└──CloudWatchBillingAlarms││││Optimization:││├──AWSTrustedAdvisor││├──AWSComputeOptimizer││├──SavingsPlans││└──ReservedInstances│└─────────────────────────────────────────────────────────────┘

AWS Cost Explorer

Features

┌─────────────────────────────────────────────────────────────┐│COSTEXPLORER││││Visualization:││├──Daily,Monthly,Yearlyviews││├──Filterbyservice,region,account,tag││├──Groupbymultipledimensions││└──Customdateranges││││Analysis:││├──Identifycostdrivers││├──Detectanomalies││├──Usagepatterns││└──Resource-levelanalysis││││Forecasting:││├──Upto12monthsforecast││├──Basedonhistoricalusage││└──Confidenceintervals││││Recommendations:││├──ReservedInstancerecommendations││├──SavingsPlansrecommendations││└──Right-sizingrecommendations│└─────────────────────────────────────────────────────────────┘

Cost Explorer API

Usecases:├──Customdashboards├──Automatedreporting├──IntegrationwithBItools└──ProgrammaticcostanalysisExamplemetrics:-GetCostAndUsage-GetCostForecast-GetReservationUtilization-GetSavingsPlansCoverage

AWS Budgets

Budget Types

┌─────────────────────────────────────────────────────────────┐│AWSBUDGETSTYPES││││1.COSTBUDGET││-Trackspendingagainstbudget││-Fixedorvariableamount││-Monthly,quarterly,yearly││││2.USAGEBUDGET││-Trackresourceusage││-EC2hours,S3storage,etc.││-Preventunexpectedusage││││3.RESERVATIONBUDGET││-RIutilizationtracking││-RIcoveragetracking││-IdentifyunderutilizedRIs││││4.SAVINGSPLANSBUDGET││-SavingsPlansutilization││-Coveragepercentage││-Identifyoptimizationopportunities│└─────────────────────────────────────────────────────────────┘

Budget Actions

Automatedresponseswhenthresholdreached:Actions:├──ApplyIAMpolicy(denynewresources)├──ApplySCP(organization-wide)├──Targetrunninginstances(stopEC2)└──SNSnotificationThresholds:├──Actualcost/usage├──Forecastedcost/usage└──Multiplethresholdsperbudget

Cost Allocation Tags

Tag Strategy

┌─────────────────────────────────────────────────────────────┐│COSTALLOCATIONTAGS││││AWS-GeneratedTags:││├──aws:createdBy││├──aws:cloudformation:stack-name││└──Automaticallyapplied││││User-DefinedTags:││├──Environment(dev,staging,prod)││├──Project/Application││├──CostCenter││├──Owner/Team││└──Department││││BestPractices:││├──Definetaggingpolicy││├──EnforceviaSCPsorConfigrules││├──UseTagPoliciesinOrganizations││└──Activatetagsforcostallocation│└─────────────────────────────────────────────────────────────┘

Purchase Options Comparison

EC2 Purchase Options

┌─────────────────────────────────────────────────────────────┐│EC2PURCHASEOPTIONS││││Option│Discount│Commitment│UseCase││────────────────┼──────────┼────────────┼─────────────────││On-Demand│0%│None│Short-term,spike││Reserved(1yr)│tới~40%│1year│Steadyworkload││Reserved(3yr)│tới72%│3years│Long-termstable││Spot│~90%│None│Flexible,fault-│││││tolerant││SavingsPlans│66%/72%│1-3years│Compute/EC2SP││DedicatedHost│Varies│Optional│License,comply││BộsốthốngnhấtvớiTuần3Ngày1(chitiếtởđó)│└─────────────────────────────────────────────────────────────┘

Reserved Instances vs Savings Plans

┌─────────────────────────────────────────────────────────────┐│RESERVEDINSTANCESvsSAVINGSPLANS││││RESERVEDINSTANCES:││├──Specificinstancetype││├──Specificregion││├──Capacityreservation(optional)││├──StandardvsConvertible││└──CansellonRIMarketplace││││SAVINGSPLANS:││├──ComputeSP:Anyinstance,anyregion││├──EC2InstanceSP:Specificfamily,anysize││├──Moreflexible││├──AppliestoLambda,Fargatetoo││└──Cannotresell││││Recommendation:││-Newworkloads→SavingsPlans(flexibility)││-ExistingRIs→Keepuntilexpiration││-Capacityneeds→ReservedInstances│└─────────────────────────────────────────────────────────────┘

Spot Instances Strategy

┌─────────────────────────────────────────────────────────────┐│SPOTINSTANCESBESTPRACTICES││││Diversification:││├──Multipleinstancetypes││├──MultipleAvailabilityZones││└──SpotFleet/EC2Fleet││││InterruptionHandling:││├──2-minutewarning(instancemetadata)││├──Checkpointing││├──Gracefulshutdownscripts││└──UseSpotwithOn-Demandfallback││││GoodUseCases:││├──Batchprocessing││├──CI/CDbuilds││├──Bigdataanalytics││├──Containerizedworkloads││└──Dev/Testenvironments││││BadUseCases:││├──Databases││├──Statefulapplications││└──Long-runningcriticaljobs│└─────────────────────────────────────────────────────────────┘

AWS Trusted Advisor

Cost Optimization Checks

┌─────────────────────────────────────────────────────────────┐│TRUSTEDADVISOR-COST││││FreeTier(Basic/Developer):││├──Servicelimits││└──Somesecuritychecks││││Business/EnterpriseSupport:││├──LowutilizationEC2instances││├──Idleloadbalancers││├──UnassociatedElasticIPs││├──UnderutilizedEBSvolumes││├──RDSidleinstances││├──ReservedInstanceoptimization││└──S3incompletemultipartuploads││││Automation:││├──TrustedAdvisorAPI││├──CloudWatchEventsintegration││└──Lambdaforauto-remediation│└─────────────────────────────────────────────────────────────┘

AWS Compute Optimizer

┌─────────────────────────────────────────────────────────────┐│COMPUTEOPTIMIZER││││Analyzes:││├──EC2instances││├──AutoScalinggroups││├──EBSvolumes││├──Lambdafunctions││└──ECSonFargate││││Recommendations:││├──Right-size(upordown)││├──Instancetypechanges││├──Costsavingsestimate││└──Performanceriskassessment││││Requirements:││├──CloudWatchmetrics≥30giờtrong14ngàygầnnhất││├──Opt-inrequired││└──Organization-wideviadelegatedadmin│└─────────────────────────────────────────────────────────────┘

AWS Cost Optimization Hub

Compute Optimizer, Savings Plans/RI recommendation, idle resource... mỗi thứ một console. Cost Optimization Hub (trong Billing and Cost Management) gom tất cả recommendation đó về một danh sách cho toàn Organization, khử trùng lặp và tính estimated savings sau khi đã trừ discount hiện có (RI/SP, EDP) — con số thực tế bạn tiết kiệm được, không phải giá niêm yết.

Nguồnrecommendation──▶CostOptimizationHub(management/delegatedaccount)├──ComputeOptimizer(right-size+idle:EC2/EBS/Lambda/ECS/RDS...)├──SavingsPlans/RIpurchaserecommendations└──Gravitonmigration,stopidleresource→Lọctheoaccount/Region/tag,sorttheosavings,exportCSV

Keyword: "single view of cost optimization opportunities across all accounts, prioritized by estimated savings after existing discounts" → Cost Optimization Hub (bật opt-in ở management account, chia sẻ cho member qua delegated administrator). Rightsizing và idle recommendation trong Cost Optimization Hub đều đến từ Compute Optimizer; Trusted Advisor không phải nguồn của Cost Optimization Hub (Trusted Advisor cost checks là kênh riêng, bản đầy đủ cần Business/Enterprise Support).

S3 Cost Optimization

┌─────────────────────────────────────────────────────────────┐│S3COSTOPTIMIZATION││││StorageClasses:││├──Standard→IA→Glacier→DeepArchive││├──UseIntelligent-Tieringforunknownpatterns││└──Lifecyclepoliciesforautomatictransitions││││DataTransfer:││├──UseVPCEndpoints(noNATcosts)││├──CloudFrontforfrequentaccess││├──Same-regionaccesscheaper││└──S3TransferAccelerationwhenneeded││││RequestCosts:││├──Batchoperations││├──S3Select(queryinplace)││└──Avoidsmallfiles(combine)││││Analysis:││├──S3StorageLens││├──S3Analytics││└──StorageClassAnalysis│└─────────────────────────────────────────────────────────────┘

Multi-Account Cost Management

┌─────────────────────────────────────────────────────────────┐│ORGANIZATIONCOSTMANAGEMENT││││ConsolidatedBilling:││├──Singlepaymentmethod││├──Combinedusageforvolumediscounts││├──ShareRIsandSavingsPlansacrossaccounts││└──Detailedbillingbyaccount││││CostAllocation:││├──Linkedaccountseparation││├──Costallocationtags││├──AWSOrganizationstagpolicies││└──Customlineitems││││Controls:││├──SCPstolimitexpensiveservices││├──Budgetsperaccount/OU││├──BudgetActionsforenforcement││└──AWSServiceCatalogforapprovedresources│└─────────────────────────────────────────────────────────────┘

Exam Scenarios

Scenario 1: Unpredictable Workload Cost Control

Requirement:ControlcostsforvariableworkloadSolution:├──AWSBudgetswithalerts├──BudgetActionstostopnon-essentialresources├──SpotInstancesforfault-tolerantcomponents├──AutoScalingwithtargettracking└──S3Intelligent-Tiering

Scenario 2: Multi-Account Cost Visibility

Requirement:Trackcostsacross100accountsSolution:├──AWSOrganizationsconsolidatedbilling├──Costallocationtags(enforcedviaTagPolicies)├──CostExplorerwithaccountfilter├──CURtoS3+Athenafordetailedanalysis└──QuickSightdashboards

Scenario 3: Optimize Long-Running Workload

Requirement:Reducecostfor24/7productionworkloadSolution:├──ComputeOptimizeranalysis├──Right-sizebasedonrecommendations├──SavingsPlansforbaselinecapacity├──ReservedInstancesifcapacityguaranteeneeded└──Spotforfault-tolerantcomponents

Quick Reference

┌─────────────────────────────────────────────────────────────┐│COSTOPTIMIZATIONCHECKLIST││││ImmediateActions:││□EnableCostExplorer││□SetupAWSBudgetswithalerts││□ReviewTrustedAdvisorrecommendations││□Deleteunusedresources││││Short-term:││□Implementtaggingstrategy││□Right-sizeinstances││□Useappropriatestorageclasses││□Reviewdatatransferpatterns││││Long-term:││□PurchaseSavingsPlans││□ReservedInstancesforstableworkloads││□Spotforfault-tolerantworkloads││□Automatecostoptimization│└─────────────────────────────────────────────────────────────┘

Câu hỏi ôn tập

  1. Compute Savings Plans vs EC2 Instance Savings Plans vs Standard RI — chọn theo tiêu chí nào?

    Xem đáp án

    Compute SP (tới ~66%): flexible nhất — áp dụng EC2 mọi family/region + Fargate + Lambda; chọn khi roadmap compute chưa chắc. EC2 Instance SP (tới ~72%): khoá family + region, đổi size/OS/AZ tự do — discount ngang Standard RI nhưng linh hoạt hơn về size. Standard RI (tới ~72%): khi cần capacity reservation (zonal RI) hoặc muốn bán lại trên RI Marketplace. Keyword "also uses Fargate and Lambda" → Compute SP; "guarantee capacity in specific AZ" → zonal RI/Capacity Reservation.

  2. Budget Actions làm được gì mà billing alarm không làm được?

    Xem đáp án

    Billing alarm chỉ notify. Budget Actions tự động can thiệp khi vượt ngưỡng (actual hoặc forecasted): (1) attach IAM policy deny tạo resource mới, (2) attach SCP lên OU (chặn cả account), (3) stop EC2/RDS instances được chỉ định. Có mode require-approval hoặc auto-execute. Đáp án cho "automatically prevent further spending when budget exceeded" — không phải Lambda tự viết.

  3. CUR khác Cost Explorer khi nào cần đến?

    Xem đáp án

    Cost Explorer: UI/API phân tích nhanh, group/filter theo dimension, forecast 12 tháng — đủ cho câu hỏi "visualize/analyze". CUR (Cost and Usage Report): file chi tiết đến từng resource-hour + tag đổ vào S3 — nguồn dữ liệu đầy đủ nhất, dùng khi cần custom analytics (Athena/QuickSight), chargeback/showback chính xác theo team, hoặc reconcile hoá đơn. Pattern chuẩn: CUR → S3 → Athena → QuickSight dashboard.

  4. RI/SP sharing trong Organizations hoạt động thế nào?

    Xem đáp án

    Trong consolidated billing, discount RI/SP mặc định share cho mọi account: account A mua RI nhưng không dùng hết, phần discount tự áp cho usage khớp ở account B. Có thể turn off sharing per account (ví dụ tách chargeback). Zonal RI còn reserve capacity thì chỉ account mua được dùng capacity đó — chỉ discount là share. Câu quiz W3: sharing mặc định bật, KHÔNG cần enable manually.

  5. FinOps team muốn một danh sách duy nhất các cơ hội tiết kiệm trên 80 account, sắp theo số tiền tiết kiệm thực tế sau khi đã tính RI/Savings Plans đang có. Dùng gì?

    Xem đáp án

    Cost Optimization Hub: gom recommendation từ Compute Optimizer (rightsizing, idle) và SP/RI purchase recommendation cho toàn Organization, khử trùng lặp, và tính savings đã trừ discount hiện hữu. Compute Optimizer một mình chỉ có right-size compute và tính theo giá On-Demand; Trusted Advisor cost checks rời rạc từng account; Cost Explorer chỉ phân tích chi phí đã phát sinh, không gom recommendation. Bật ở management account hoặc delegated administrator cho Billing.

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

  1. Budget + Budget Action: tạo cost budget $10/tháng với 2 threshold (80% notify SNS, 100% auto áp IAM deny policy tạo EC2 mới lên một test role); verify role bị chặn khi trigger.

  2. CUR + Athena: bật CUR (Parquet, hourly, resource IDs) vào S3; dùng template CloudFormation của AWS tạo Athena table và chạy query "top 10 resource theo chi phí tháng này".

  3. Tag enforcement: tạo Tag Policy trong Organizations yêu cầu tag CostCenter, kết hợp SCP deny ec2:RunInstances khi thiếu tag (aws:RequestTag); test launch instance thiếu tag bị từ chối, rồi activate tag trong Billing để dùng được trong Cost Explorer.

Tài liệu tham khảo


Bài tiếp theo →