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

时间:2016-02-09 13:54:37

标签: java amazon-web-services amazon-s3 aws-sdk amazon-cloudwatch

我发现AWS云手表收集了结算指标,但无法找到任何api引用以便以编程方式使用它们。我希望它们像量度指标,实例指标一样作为指标而不是S3存储桶中的CSV格式。有没有办法实现这个目标?

1 个答案:

答案 0 :(得分:0)

首先,要记住两件事:

  1. 根据this文档,从单个GetMetricStatistics请求返回的最大数据点数为1,440。因此,您不能例如在5分钟内查询一周内的数据(因为这将是2,016个数据点)。
  2. 要获取结算指标,您可以申请所有服务的估算费用总额或每项服务的估算费用。如上所述here
  3. 此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);
        }
    }