如何通过AWS API获取单台EC2实例成本而非所有EC2总费用
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:
Filter for EC2 Service + Target Instance ID
EC2's service identifier in Cost Explorer isAmazon Elastic Compute Cloud - Compute(not just "EC2"). Pair that with a filter on theINSTANCE_IDdimension to isolate your specific instance.Group by Instance ID
AddingINSTANCE_IDto yourGroupByensures the response breaks out costs specifically for that instance, rather than aggregating all EC2 instances.Specify Relevant Metrics
Include metrics likeUnblendedCost(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:GetCostAndUsagepermission to call this API.
内容的提问来源于stack exchange,提问作者Leo

