1

I want to get the usage and cost of my EC2 instances using the Cost Explorer API.

I am able to get the usage and cost successfully but that cost and usage includes the amount of usage done by EC2 instance and EBS volumes, so I wanted to seperate the cost using usage_type_group such as EC2 :Running Hours but whenever I pass that I don't get any value. If I remove that I get the value with total usage and cost.

DimensionValues dimensions = new DimensionValues();
        dimensions.setKey("USAGE_TYPE_GROUP");
        Collection<String> values = new ArrayList<>();
        values.add("EC2 : Running Hours");
        dimensions.setValues(values);
        filter.setDimensions(dimensions);
        GetCostAndUsageRequest getCostAndUsageRequest = new GetCostAndUsageRequest().withGroupBy(groupBy)

                .withTimePeriod(dateInterval).withGranularity(Granularity.MONTHLY)
                .withFilter(filter)
                .withMetrics("UsageQuantity")
                .withMetrics("BlendedCost");

        try {
            costInformation = costExplorer.getCostAndUsage(getCostAndUsageRequest);
        } catch (AWSCostExplorerException ex) {
            logger.error("cost fetch details failed from cost explorer " + ex.getErrorMessage());
        }
John Rotenstein
  • 241,921
  • 22
  • 380
  • 470
Vatsal Rahul
  • 347
  • 1
  • 4
  • 19
  • I think it should be "USAGE_TYPE" and check the values whether its the right value. I found that here. Try taking a look there. https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_Expression.html – Althaf1467 Oct 28 '19 at 11:50
  • I will try it out , although USAGE_TYPE and USAGE_TYPE_GROUP has different values , but still i can give a try – Vatsal Rahul Oct 28 '19 at 12:10

1 Answers1

3

Try this out. I did this and got some EC2 billing information.

void test_costDetails() {
        Expression expression = new Expression();
        DimensionValues dimensions = new DimensionValues();
        dimensions.withKey(Dimension.SERVICE);
        dimensions.withValues("EC2 - Other");

        expression.withDimensions(dimensions);
        GetCostAndUsageResult result = costExplorer.getCostAndUsage(new GetCostAndUsageRequest().withTimePeriod(
                new DateInterval().withStart("2019-10-01").withEnd("2019-10-29")).withGranularity("DAILY").withMetrics(
                        "BlendedCost").withFilter(expression));

        result.getResultsByTime().forEach(r -> {
            System.out.println(r);
        });
    }
Althaf1467
  • 281
  • 1
  • 14