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());
}
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);
});
}