You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过AWS API获取单台EC2实例成本而非所有EC2总费用

How to Fetch Cost for a Single EC2 Instance with AWS Cost Explorer's GetCostAndUsage API

Got it, let's walk through exactly how to get cost data for a single EC2 instance using the GetCostAndUsage API. Here's what you need to adjust in your request:

Key Configurations to Target a Single EC2 Instance

First, you need to narrow down the scope to your specific instance by combining filters and grouping correctly:

  1. Filter for EC2 Service + Target Instance ID
    EC2's service identifier in Cost Explorer is Amazon Elastic Compute Cloud - Compute (not just "EC2"). Pair that with a filter on the INSTANCE_ID dimension to isolate your specific instance.

  2. Group by Instance ID
    Adding INSTANCE_ID to your GroupBy ensures the response breaks out costs specifically for that instance, rather than aggregating all EC2 instances.

  3. Specify Relevant Metrics
    Include metrics like UnblendedCost (your actual out-of-pocket cost) to get clear, actionable cost data.

Example Request JSON

Here's a complete, adjusted request that targets a single EC2 instance:

{
  "TimePeriod": {
    "Start": "2024-05-01",
    "End": "2024-06-01"
  },
  "Granularity": "MONTHLY",
  "Filter": {
    "And": [
      {
        "Dimensions": {
          "Key": "SERVICE",
          "Values": [
            "Amazon Elastic Compute Cloud - Compute"
          ]
        }
      },
      {
        "Dimensions": {
          "Key": "INSTANCE_ID",
          "Values": [
            "i-0123456789abcdef0"
          ]
        }
      }
    ]
  },
  "GroupBy": [
    {
      "Type": "DIMENSION",
      "Key": "INSTANCE_ID"
    }
  ],
  "Metrics": [
    "UnblendedCost"
  ]
}

Important Notes

  • Double-check the Instance ID: Make sure the ID matches exactly what's shown in the EC2 Console (case-sensitive, no extra spaces).
  • Cost Data Delay: Cost Explorer typically has a 24-48 hour delay, so you won't see real-time costs.
  • Associated Resources: This request will include costs tied directly to the instance (like attached EBS volumes created with the instance). If you have standalone EBS volumes linked to the instance, you might need additional filters to include those if they aren't already associated via the instance ID dimension.
  • Permissions: Ensure your IAM role/user has the ce:GetCostAndUsage permission to call this API.

内容的提问来源于stack exchange,提问作者Leo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:19:49