· 6 years ago · Mar 04, 2019, 10:44 AM
1public Map<String, List<String>> costApi(String instanceName, String startDate, String terminationDate,
2 String instanceType, String accessKey, String secretKey) {
3
4 DateFormatter dateFormatter = new DateFormatter();
5
6 startDate = dateFormatter.previousDay(startDate);
7 terminationDate = dateFormatter.nextDay(terminationDate);
8
9 logger.info("Cost api fields: instanceName : " + instanceName + "startDate : " + startDate
10 + "terminationDate : " + terminationDate + "instanceType : " + instanceType);
11
12 Map<String, List<String>> costAndUsage = new HashMap<String, List<String>>();
13 List<String> listOfUsageAndCost = new ArrayList<String>();
14 AWSCostExplorer awsCostExplorer = AWSCostExplorerClientBuilder.standard()
15 .withCredentials(new AWSCredentialsProvider() {
16 @Override
17 public void refresh() {
18 }
19
20 @Override
21 public AWSCredentials getCredentials() {
22 AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);
23 return awsCredentials;
24 }
25 }).withRegion(Regions.US_EAST_1).build();
26
27 List<String> instances = new ArrayList<String>();
28 instances.add(instanceName);//
29 DateInterval dateInterval = new DateInterval().withStart(startDate).withEnd(terminationDate);
30 List<String> instanceTypeValues = new ArrayList<String>();
31 instanceTypeValues.add("BoxUsage:" + instanceType + " (Hrs)");
32 TagValues values = new TagValues().withKey("Name").withValues(instances);// i-048cc6a6987559c28
33 Expression exp = new Expression().withTags(values);
34
35 GetCostAndUsageRequest getCostAndUsageRequest = new GetCostAndUsageRequest().withFilter(exp)
36 .withTimePeriod(dateInterval).withGranularity(Granularity.MONTHLY).withMetrics("UsageQuantity")
37 .withMetrics("BlendedCost");
38
39 GetCostAndUsageResult str = awsCostExplorer.getCostAndUsage(getCostAndUsageRequest);
40
41 logger.info("costUsageResponse is : " + str);
42
43 Gson g = new Gson();
44
45 String jsonString = g.toJson(str);
46
47 logger.info("jsonString : " + jsonString);
48
49 JSONObject jsonResponse;
50 JSONArray result;
51 JSONObject resultsByTime;
52 JSONObject total;
53 JSONObject blendedCost = null;
54 JSONObject usageQuantity = null;
55
56 ObjectMapper objectMapper = new ObjectMapper();
57 JsonNode blendedCostRootNode = null;
58 JsonNode usageQuantityRootNode = null;
59 JsonNode cost = null;
60 JsonNode usage = null;
61 Double totalCost = 0.0;
62 Double totalRunningTime = 0.0;
63 try {
64 jsonResponse = new JSONObject(jsonString.toString());
65 result = jsonResponse.getJSONArray("resultsByTime");
66 for (int i = 0; i < result.length(); i++) {
67 resultsByTime = result.getJSONObject(i);
68 total = resultsByTime.getJSONObject("total");
69 blendedCost = total.getJSONObject("BlendedCost");
70 usageQuantity = total.getJSONObject("UsageQuantity");
71
72 logger.info("blendedCost : " + blendedCost);
73 logger.info("usageQuantity : " + usageQuantity);
74
75 try {
76 blendedCostRootNode = objectMapper.readTree(blendedCost.toString());
77 usageQuantityRootNode = objectMapper.readTree(usageQuantity.toString());
78 } catch (IOException e) {
79 e.printStackTrace();
80 logger.error("Error", e);
81 }
82
83 cost = blendedCostRootNode.path("amount");
84 logger.info("Cost = " + cost);
85 totalCost = totalCost + cost.asDouble();
86
87 usage = usageQuantityRootNode.path("amount");
88 logger.info("Usage = " + usage);
89 totalRunningTime = totalRunningTime +usage.asDouble();
90 }
91 } catch (JSONException e) {
92 e.printStackTrace();
93 }
94
95 logger.info("Total Cost is : " +totalCost);
96 logger.info("Total Running time is : " +totalRunningTime);
97
98 listOfUsageAndCost.add(totalRunningTime.toString().replace(""", ""));
99 listOfUsageAndCost.add(totalCost.toString().replace(""", ""));
100 costAndUsage.put(instanceName, listOfUsageAndCost);
101
102 return costAndUsage;
103}
104
105response = client.get_cost_and_usage(
106TimePeriod={
107 'Start': 'string',
108 'End': 'string'
109},
110Granularity='DAILY'|'MONTHLY'|'HOURLY',
111Filter={
112 'Or': [
113 {'... recursive ...'},
114 ],
115 'And': [
116 {'... recursive ...'},
117 ],
118 'Not': {'... recursive ...'},
119 'Dimensions': {
120 'Key': 'AZ'|'INSTANCE_TYPE'|'LINKED_ACCOUNT'|'OPERATION'|'PURCHASE_TYPE'|'REGION'|'SERVICE'|'USAGE_TYPE'|'USAGE_TYPE_GROUP'|'RECORD_TYPE'|'OPERATING_SYSTEM'|'TENANCY'|'SCOPE'|'PLATFORM'|'SUBSCRIPTION_ID'|'LEGAL_ENTITY_NAME'|'DEPLOYMENT_OPTION'|'DATABASE_ENGINE'|'CACHE_ENGINE'|'INSTANCE_TYPE_FAMILY'|'BILLING_ENTITY'|'RESERVATION_ID',
121 'Values': [
122 'string',
123 ]
124 },
125 'Tags': {
126 'Key': 'string',
127 'Values': [
128 'string',
129 ]
130 }
131},
132Metrics=[
133 'string',
134],
135GroupBy=[
136 {
137 'Type': 'DIMENSION'|'TAG',
138 'Key': 'string'
139 },
140],
141NextPageToken='string'