如何通过 JAVA API 获取 AWS Billing 指标

How to get AWS Billing metrics through JAVA API

我发现 AWS 云监视收集计费指标,但找不到任何 api 引用来以编程方式使用它们。我希望它们像卷指标、实例指标一样作为指标,但不是 S3 存储桶中的 CSV 格式。有什么办法可以实现吗?

首先,要记住两件事:

  1. 根据 this 文档,单个 GetMetricStatistics 请求返回的最大数据点数为 1,440。因此,例如,您不能在 5 分钟的时间内查询一周的数据(因为这将是 2,016 个数据点)。
  2. 要获取计费指标,您可以请求所有服务的预估费用总额或每项服务的预估费用。如所述 here

此 Java 8 示例检索过去两周内所有服务的预估总费用,时间间隔为 12 小时。

import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.cloudwatch.AmazonCloudWatchClient;
import com.amazonaws.services.cloudwatch.model.Datapoint;
import com.amazonaws.services.cloudwatch.model.Dimension;
import com.amazonaws.services.cloudwatch.model.GetMetricStatisticsRequest;
import com.amazonaws.services.cloudwatch.model.GetMetricStatisticsResult;
import java.util.Collections;
import java.util.Date;

public class AWSCloudWatchBillingService { 

    public static void main(String[] args) {
        final String awsAccessKey = "<YOUR_AWS_ACCESS_KEY>";
        final String awsSecretKey = "<YOUR_AWS_SECRET_ACCESS_KEY>";

        final AmazonCloudWatchClient client = client(awsAccessKey, awsSecretKey);
        final GetMetricStatisticsRequest request = request(); 
        final GetMetricStatisticsResult result = result(client, request);
        printIt(result);   
    }

    private static AmazonCloudWatchClient client(final String awsAccessKey, final String awsSecretKey) {
        final AmazonCloudWatchClient client = new AmazonCloudWatchClient(new BasicAWSCredentials(awsAccessKey, awsSecretKey));
        client.setEndpoint("http://monitoring.us-east-1.amazonaws.com/");
        return client;
    }

    private static GetMetricStatisticsRequest request() {
        final long twoWeeks = 1000 * 60 * 60 * 24 * 15;
        final int twelveHours = 60 * 60 * 12;
        return new GetMetricStatisticsRequest()
            .withStartTime(new Date(new Date().getTime() - twoWeeks))
            .withNamespace("AWS/Billing")
            .withPeriod(twelveHours)
            .withDimensions(new Dimension().withName("Currency").withValue("USD"))
            .withMetricName("EstimatedCharges")
            .withStatistics("Average", "Maximum")
            .withEndTime(new Date());
    }

    private static GetMetricStatisticsResult result(
            final AmazonCloudWatchClient client, final GetMetricStatisticsRequest request) {
         return client.getMetricStatistics(request);
    }

    private static void printIt(final GetMetricStatisticsResult result) {
        Collections.sort(result.getDatapoints(), (Datapoint dp1, Datapoint dp2) -> dp1.getTimestamp().compareTo(dp2.getTimestamp()));
        System.out.println("**************************************"); 
        System.out.println(result);
    }
}