Skip to content

Cloud Cost Management

Tools and strategies for monitoring, optimizing, and controlling cloud costs across AWS, Azure, and GCP.

AWS Cost Management

AWS Cost Explorer

COMMANDDESCRIPTION
Open Cost Explorer ConsoleNavigate to Billing & Cost Management > Cost Explorer
aws ce get-cost-and-usage --time-period Start=2024-01-01,End=2024-01-31Get cost and usage data
aws ce get-cost-and-usage --granularity MONTHLY --metrics BlendedCostGet monthly cost
aws ce get-dimension-values --dimension SERVICE --time-period Start=2024-01-01,End=2024-01-31List services with costs

AWS Billing Commands

COMMANDDESCRIPTION
aws ce get-cost-and-usage --filter '{\"Dimensions\":{\"Key\":\"SERVICE\",\"Values\":[\"Amazon EC2\"]}}'Filter by service
aws ce get-cost-and-usage --group-by Type,DIMENSION --key SERVICEGroup by service
aws ce get-cost-and-usage --metrics "UnblendedCost,UsageQuantity"Get multiple metrics

AWS Budgets

COMMANDDESCRIPTION
Navigate to Billing & Cost Management > BudgetsCreate and manage budgets
aws budgets create-budget --account-id <account-id> --budget file://budget.jsonCreate budget via CLI
aws budgets describe-budgets --account-id <account-id>List all budgets
aws budgets describe-budget --account-id <account-id> --budget-name MyBudgetDescribe specific budget
aws budgets delete-budget --account-id <account-id> --budget-name MyBudgetDelete budget

AWS Budget JSON Example

json
{
  "BudgetName": "MonthlyCostBudget",
  "BudgetLimit": {
    "Amount": "100",
    "Unit": "USD"
  },
  "TimeUnit": "MONTHLY",
  "TimePeriod": {
    "Start": "2024-01-01T00:00:00Z",
    "End": "2024-12-31T23:59:59Z"
  },
  "CostFilters": {},
  "CostTypes": {
    "IncludeTax": false,
    "IncludeSubscription": false,
    "UseBlended": false
  },
  "NotificationWithSubscribers": [
    {
      "Notification": {
        "NotificationType": "ACTUAL",
        "ComparisonOperator": "GREATER_THAN",
        "Threshold": 80,
        "ThresholdType": "PERCENTAGE_OF_BUDGET"
      },
      "Subscribers": [
        {
          "SubscriptionType": "EMAIL",
          "Address": "alerts@example.com"
        }
      ]
    }
  ]
}

AWS Cost Optimization Tools

ToolDescription
AWS Cost ExplorerAnalyze costs and usage trends
AWS BudgetsSet cost thresholds and alerts
AWS Trusted AdvisorCost optimization recommendations
AWS Compute OptimizerOptimize EC2 instances
AWS Savings PlansCommit to 1-3 years for discounts
Reserved InstancesReserve capacity for discounts
Spot InstancesUp to 90% off EC2 prices

AWS Trusted Advisor Cost Checks

CheckDescription
Low Utilization Amazon EC2 InstancesIdentify underutilized EC2 instances
Amazon EBS Provisioned IOPS (SSD) VolumesIdentify underutilized EBS volumes
Idle Load BalancersIdentify unused load balancers
Unassociated Elastic IP AddressesIdentify unused Elastic IPs
Underutilized Amazon RDS InstancesIdentify underutilized RDS instances

Azure Cost Management

Azure Cost Management Portal

ActionLocation
View costsCost Management + Billing > Cost Management
Set budgetsCost Management + Billing > Cost Management > Budgets
View recommendationsCost Management + Billing > Cost Management > Recommendations
Export costsCost Management + Billing > Cost Management > Exports

Azure Cost Management Commands

COMMANDDESCRIPTION
az consumption usage list --start-date 2024-01-01 --end-date 2024-01-31List usage details
az consumption prices list --meter-id <meter-id>Get pricing info
az billing account listList billing accounts
az billing subscription listList subscriptions
az costmanagement budget create --name MyBudget --amount 100 --category costCreate budget
az costmanagement budget listList budgets
az costmanagement budget show --name MyBudgetShow budget details

Azure Budget Creation

bash
az costmanagement budget create \
  --name MonthlyCostBudget \
  --scope /subscriptions/{subscription-id} \
  --amount 100 \
  --currency USD \
  --time-grain Monthly \
  --notification-email alerts@example.com \
  --notification-threshold 80

Azure Cost Analysis

MetricDescription
Actual CostTotal cost incurred
Amortized CostTotal cost including amortized upfront fees
Forecasted CostPredicted future costs
Cost TrendCost changes over time

Azure Cost Optimization Tools

ToolDescription
Azure Cost ManagementAnalyze and manage costs
Azure BudgetsSet spending limits and alerts
Azure AdvisorCost optimization recommendations
Azure Reserved InstancesReserve VM instances for discounts
Azure Savings PlansCommit to compute usage for discounts
Azure Spot InstancesUp to 90% off VM prices

Google Cloud Cost Management

GCP Billing Console

ActionLocation
View costsBilling > Reports
Set budgetsBilling > Budgets & alerts
Export costsBilling > Export billing data
Payment setupBilling > Payment methods

GCP Billing Commands

COMMANDDESCRIPTION
gcloud billing accounts listList billing accounts
gcloud billing projects link <project-id> --billing-account <account-id>Link project to billing account
gcloud billing budgets create --billing-account <account-id> --display-name "MyBudget" --amount-usd 100Create budget
gcloud billing budgets list --billing-account <account-id>List budgets
gcloud billing budgets describe <budget-id> --billing-account <account-id>Describe budget

GCP Cost Analysis

MetricDescription
CostActual costs incurred
CreditApplied credits and promotions
ForecastPredicted future costs
Committed use discountsSavings from commitments

GCP Cost Optimization Tools

ToolDescription
GCP Billing ReportsDetailed cost analysis
GCP BudgetsSet cost alerts and thresholds
GCP RecommendationsCost optimization suggestions
Committed Use DiscountsCommit to 1-3 years for discounts
Sustained Use DiscountsAutomatic discounts for sustained usage
Preemptible InstancesUp to 80% off compute prices

Cost Optimization Strategies

1. Right-Size Resources

StrategyDescriptionSavings
Instance RightsizingUse appropriately sized instances20-40%
Storage TiersUse appropriate storage class30-50%
Remove Idle ResourcesDelete unused resources100%

2. Use Savings Plans and Reserved Instances

TypeCommitmentDiscountBest For
Compute Savings Plans1-3 yearsUp to 72%Steady EC2/ECS/Lambda usage
Reserved Instances1-3 yearsUp to 75%Long-running EC2 instances
Committed Use Discounts1-3 yearsUp to 70%Steady GCP compute usage

3. Use Spot/Preemptible Instances

ProviderProductDiscountBest For
AWSSpot InstancesUp to 90%Fault-tolerant workloads
AzureSpot VMsUp to 90%Batch processing, testing
GCPPreemptible InstancesUp to 80%Batch processing, testing

Use Cases:

  • Batch processing jobs
  • CI/CD workloads
  • Big data processing
  • Distributed computing
  • Development/testing

4. Optimize Storage

StrategyDescriptionSavings
Lifecycle PoliciesMove old data to cheaper storage40-60%
Delete Unused DataRemove old snapshots, logs100%
Use Appropriate TiersHot, Cool, Archive storage20-50%

Storage Tiers (AWS):

  • Standard: Frequently accessed
  • Intelligent-Tiering: Automatic tiering
  • Standard-IA: Infrequently accessed
  • Glacier: Long-term archival

5. Auto-Scaling

StrategyDescription
Auto Scaling GroupsScale instances based on demand
Kubernetes HPAHorizontal pod autoscaling
Serverless FunctionsPay per execution
Scheduled ScalingScale during business hours

Monitoring and Alerting

Cost Monitoring Dashboards

ProviderTool
AWSCost Explorer, CloudWatch
AzureCost Management, Azure Monitor
GCPBilling Reports, Cloud Monitoring

Cost Alerts

ProviderAlert TypeRecommended Threshold
AWSBudget alert80% of budget
AzureBudget alert80% of budget
GCPBudget alert80% of budget
AWSAnomaly detection>50% increase from baseline
AzureAnomaly detection>50% increase from baseline

Cost Anomaly Detection

ProviderTool
AWSAWS Cost Anomaly Detection
AzureAzure Cost Management Anomaly Detection
GCPGCP Budget anomaly alerts

Tagging Strategy

Tagging Best Practices

Best PracticeDescription
Tag all resourcesEnable cost allocation
Use consistent namingStandardize tag keys
Business tagsCost center, project, owner
Technical tagsEnvironment, application, tier
Mandatory tagsEnforce via policies
Automated taggingTag on resource creation

Common Tags

TagExamplePurpose
Environmentdev, staging, prodSeparate environment costs
Projectwebsite, api, backendProject-level cost allocation
CostCenterIT001, SALES002Business unit cost tracking
Ownerdevops-team, team-aResponsibility assignment
Applicationapp-service, databaseApplication-level tracking
Tierfrontend, backend, dataMulti-tier cost analysis

Tagging Enforcement

ProviderTool
AWSAWS Config rules, SCPs
AzureAzure Policy
GCPOrganization policies

Cost Analysis Queries

AWS Cost and Usage Queries

bash
# Get daily costs by service
aws ce get-cost-and-usage \
  --time-period Start=2024-01-01,End=2024-01-31 \
  --granularity DAILY \
  --metrics BlendedCost \
  --group-by Type=DIMENSION,Key=SERVICE

# Get costs by tag
aws ce get-cost-and-usage \
  --time-period Start=2024-01-01,End=2024-01-31 \
  --granularity MONTHLY \
  --metrics BlendedCost \
  --filter '{\"Tags\":{\"Key\":\"Environment\",\"Values\":[\"prod\"]}}'

# Get forecasted costs
aws ce get-cost-and-usage \
  --time-period Start=2024-01-01,End=2024-12-31 \
  --granularity MONTHLY \
  --metrics BlendedCost \
  --prediction

Azure Cost Queries

bash
# Get subscription costs
az consumption usage list \
  --start-date 2024-01-01 \
  --end-date 2024-01-31

# Get cost by resource group
az consumption usage list \
  --start-date 2024-01-01 \
  --end-date 2024-01-31 | jq 'group_by(.properties.resourceGroup)'

# Get budget status
az costmanagement budget list --scope "/subscriptions/{subscription-id}"

GCP Cost Queries

bash
# Get project costs
bq query \
  --project_id=<billing-project-id> \
  "SELECT
     project.id as project_id,
     invoice.month as month,
     SUM(cost) as total_cost
   FROM `<billing-export-dataset>`
   WHERE invoice.month = '202401'
   GROUP BY project_id, month"

# Get costs by label
bq query \
  --project_id=<billing-project-id> \
  "SELECT
     labels.value as environment,
     SUM(cost) as total_cost
   FROM `<billing-export-dataset>`
   WHERE labels.key = 'environment'
   GROUP BY labels.value"

Common Cost Issues and Solutions

IssueRoot CauseSolution
Unexpected high costsUnoptimized instancesRight-size, use Savings Plans
Data transfer costsCross-region transfersUse regional resources, CDN
Storage costs growingOld data retentionLifecycle policies, deletion
Idle resourcesForgotten resourcesAutomate cleanup, monitoring
Development costs highProduction configs in devSeparate environments, tags

Cost Management Best Practices

  1. Monitor regularly - Review costs weekly or monthly
  2. Set budgets - Create budgets for all projects
  3. Use alerts - Notify team of cost anomalies
  4. Tag everything - Enable cost allocation
  5. Review recommendations - Act on provider suggestions
  6. Use savings plans - Commit to predictable workloads
  7. Right-size resources - Match resources to needs
  8. Clean up unused - Remove idle resources regularly
  9. Automate cost optimization - Use scripts and tools
  10. Educate team - Train on cost awareness

Additional Resources

ProviderDocumentation
AWS Cost Managementhttps://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/
Azure Cost Managementhttps://docs.microsoft.com/azure/cost-management-billing/
GCP Billinghttps://cloud.google.com/billing/docs
AWS Pricing Calculatorhttps://calculator.aws/
Azure Pricing Calculatorhttps://azure.microsoft.com/pricing/calculator/
GCP Pricing Calculatorhttps://cloud.google.com/products/calculator/

Released under MIT License.