devHọc Dev
Bài học

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

Tuần 8 – Ngày 4

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

AWSCOSTMANAGEMENTTOOLSPlanning&Budgeting:AWSPricingCalculatorAWSBudgetsCostAllocationTagsMonitoring&Analysis:AWSCostExplorerAWSCostandUsageReport(CUR)CloudWatchBillingAlarmsOptimization:AWSTrustedAdvisorAWSComputeOptimizerSavingsPlansReservedInstances

AWS Cost Explorer

Features

COSTEXPLORERVisualization:Daily,Monthly,YearlyviewsFilterbyservice,region,account,tagGroupbymultipledimensionsCustomdaterangesAnalysis:IdentifycostdriversDetectanomaliesUsagepatternsResource-levelanalysisForecasting:Upto12monthsforecastBasedonhistoricalusageConfidenceintervalsRecommendations:ReservedInstancerecommendationsSavingsPlansrecommendationsRight-sizingrecommendations

Cost Explorer API

Usecases:CustomdashboardsAutomatedreportingIntegrationwithBItoolsProgrammaticcostanalysisExamplemetrics:-GetCostAndUsage-GetCostForecast-GetReservationUtilization-GetSavingsPlansCoverage

AWS Budgets

Budget Types

AWSBUDGETSTYPES1.COSTBUDGET-Trackspendingagainstbudget-Fixedorvariableamount-Monthly,quarterly,yearly2.USAGEBUDGET-Trackresourceusage-EC2hours,S3storage,etc.-Preventunexpectedusage3.RESERVATIONBUDGET-RIutilizationtracking-RIcoveragetracking-IdentifyunderutilizedRIs4.SAVINGSPLANSBUDGET-SavingsPlansutilization-Coveragepercentage-Identifyoptimizationopportunities

Budget Actions

Automatedresponseswhenthresholdreached:Actions:ApplyIAMpolicy(denynewresources)ApplySCP(organization-wide)Targetrunninginstances(stopEC2)SNSnotificationThresholds:Actualcost/usageForecastedcost/usageMultiplethresholdsperbudget

Cost Allocation Tags

Tag Strategy

COSTALLOCATIONTAGSAWS-GeneratedTags:aws:createdByaws:cloudformation:stack-nameAutomaticallyappliedUser-DefinedTags:Environment(dev,staging,prod)Project/ApplicationCostCenterOwner/TeamDepartmentBestPractices:DefinetaggingpolicyEnforceviaSCPsorConfigrulesUseTagPoliciesinOrganizationsActivatetagsforcostallocation

Purchase Options Comparison

EC2 Purchase Options

EC2PURCHASEOPTIONSOptionDiscountCommitmentUseCaseOn-Demand0%NoneShort-term,spikeReserved(1yr)~40%1yearSteadyworkloadReserved(3yr)~60%3yearsLong-termstableSpot~90%NoneFlexible,fault-tolerantSavingsPlans~40-60%1-3yearsFlexibleusageDedicatedHostVariesOptionalLicense,comply

Reserved Instances vs Savings Plans

RESERVEDINSTANCESvsSAVINGSPLANSRESERVEDINSTANCES:SpecificinstancetypeSpecificregionCapacityreservation(optional)StandardvsConvertibleCansellonRIMarketplaceSAVINGSPLANS:ComputeSP:Anyinstance,anyregionEC2InstanceSP:Specificfamily,anysizeMoreflexibleAppliestoLambda,FargatetooCannotresellRecommendation:-NewworkloadsSavingsPlans(flexibility)-ExistingRIsKeepuntilexpiration-CapacityneedsReservedInstances

Spot Instances Strategy

SPOTINSTANCESBESTPRACTICESDiversification:MultipleinstancetypesMultipleAvailabilityZonesSpotFleet/EC2FleetInterruptionHandling:2-minutewarning(instancemetadata)CheckpointingGracefulshutdownscriptsUseSpotwithOn-DemandfallbackGoodUseCases:BatchprocessingCI/CDbuildsBigdataanalyticsContainerizedworkloadsDev/TestenvironmentsBadUseCases:DatabasesStatefulapplicationsLong-runningcriticaljobs

AWS Trusted Advisor

Cost Optimization Checks

TRUSTEDADVISOR-COSTFreeTier(Basic/Developer):ServicelimitsSomesecuritychecksBusiness/EnterpriseSupport:LowutilizationEC2instancesIdleloadbalancersUnassociatedElasticIPsUnderutilizedEBSvolumesRDSidleinstancesReservedInstanceoptimizationS3incompletemultipartuploadsAutomation:TrustedAdvisorAPICloudWatchEventsintegrationLambdaforauto-remediation

AWS Compute Optimizer

COMPUTEOPTIMIZERAnalyzes:EC2instancesAutoScalinggroupsEBSvolumesLambdafunctionsECSonFargateRecommendations:Right-size(upordown)InstancetypechangesCostsavingsestimatePerformanceriskassessmentRequirements:CloudWatchmetrics(14daysminimum)Opt-inrequiredOrganization-wideviadelegatedadmin

S3 Cost Optimization

S3COSTOPTIMIZATIONStorageClasses:StandardIAGlacierDeepArchiveUseIntelligent-TieringforunknownpatternsLifecyclepoliciesforautomatictransitionsDataTransfer:UseVPCEndpoints(noNATcosts)CloudFrontforfrequentaccessSame-regionaccesscheaperS3TransferAccelerationwhenneededRequestCosts:BatchoperationsS3Select(queryinplace)Avoidsmallfiles(combine)Analysis:S3StorageLensS3AnalyticsStorageClassAnalysis

Multi-Account Cost Management

ORGANIZATIONCOSTMANAGEMENTConsolidatedBilling:SinglepaymentmethodCombinedusageforvolumediscountsShareRIsandSavingsPlansacrossaccountsDetailedbillingbyaccountCostAllocation:LinkedaccountseparationCostallocationtagsAWSOrganizationstagpoliciesCustomlineitemsControls:SCPstolimitexpensiveservicesBudgetsperaccount/OUBudgetActionsforenforcementAWSServiceCatalogforapprovedresources

Exam Scenarios

Scenario 1: Unpredictable Workload Cost Control

Requirement:ControlcostsforvariableworkloadSolution:AWSBudgetswithalertsBudgetActionstostopnon-essentialresourcesSpotInstancesforfault-tolerantcomponentsAutoScalingwithtargettrackingS3Intelligent-Tiering

Scenario 2: Multi-Account Cost Visibility

Requirement:Trackcostsacross100accountsSolution:AWSOrganizationsconsolidatedbillingCostallocationtags(enforcedviaTagPolicies)CostExplorerwithaccountfilterCURtoS3+AthenafordetailedanalysisQuickSightdashboards

Scenario 3: Optimize Long-Running Workload

Requirement:Reducecostfor24/7productionworkloadSolution:ComputeOptimizeranalysisRight-sizebasedonrecommendationsSavingsPlansforbaselinecapacityReservedInstancesifcapacityguaranteeneededSpotforfault-tolerantcomponents

Quick Reference

COSTOPTIMIZATIONCHECKLISTImmediateActions:EnableCostExplorerSetupAWSBudgetswithalertsReviewTrustedAdvisorrecommendationsDeleteunusedresourcesShort-term:ImplementtaggingstrategyRight-sizeinstancesUseappropriatestorageclassesReviewdatatransferpatternsLong-term:PurchaseSavingsPlansReservedInstancesforstableworkloadsSpotforfault-tolerantworkloadsAutomatecostoptimization

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.

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 chính thức


Tiếp theo: Quiz Tuần 8