Я пытаюсь получить стоимость экземпляра ec2 (через проводник затрат) и использую api стоимости и использования (с python) для каждого имени экземпляра.Я успешно прошел через Java.
Ниже мой Java-код:
public Map<String, List<String>> costApi(String instanceName, String startDate, String terminationDate,
String instanceType, String accessKey, String secretKey) {
DateFormatter dateFormatter = new DateFormatter();
startDate = dateFormatter.previousDay(startDate);
terminationDate = dateFormatter.nextDay(terminationDate);
logger.info("Cost api fields: instanceName : " + instanceName + "startDate : " + startDate
+ "terminationDate : " + terminationDate + "instanceType : " + instanceType);
Map<String, List<String>> costAndUsage = new HashMap<String, List<String>>();
List<String> listOfUsageAndCost = new ArrayList<String>();
AWSCostExplorer awsCostExplorer = AWSCostExplorerClientBuilder.standard()
.withCredentials(new AWSCredentialsProvider() {
@Override
public void refresh() {
}
@Override
public AWSCredentials getCredentials() {
AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);
return awsCredentials;
}
}).withRegion(Regions.US_EAST_1).build();
List<String> instances = new ArrayList<String>();
instances.add(instanceName);//
DateInterval dateInterval = new DateInterval().withStart(startDate).withEnd(terminationDate);
List<String> instanceTypeValues = new ArrayList<String>();
instanceTypeValues.add("BoxUsage:" + instanceType + " (Hrs)");
TagValues values = new TagValues().withKey("Name").withValues(instances);// i-048cc6a6987559c28
Expression exp = new Expression().withTags(values);
GetCostAndUsageRequest getCostAndUsageRequest = new GetCostAndUsageRequest().withFilter(exp)
.withTimePeriod(dateInterval).withGranularity(Granularity.MONTHLY).withMetrics("UsageQuantity")
.withMetrics("BlendedCost");
GetCostAndUsageResult str = awsCostExplorer.getCostAndUsage(getCostAndUsageRequest);
logger.info("costUsageResponse is : " + str);
Gson g = new Gson();
String jsonString = g.toJson(str);
logger.info("jsonString : " + jsonString);
JSONObject jsonResponse;
JSONArray result;
JSONObject resultsByTime;
JSONObject total;
JSONObject blendedCost = null;
JSONObject usageQuantity = null;
ObjectMapper objectMapper = new ObjectMapper();
JsonNode blendedCostRootNode = null;
JsonNode usageQuantityRootNode = null;
JsonNode cost = null;
JsonNode usage = null;
Double totalCost = 0.0;
Double totalRunningTime = 0.0;
try {
jsonResponse = new JSONObject(jsonString.toString());
result = jsonResponse.getJSONArray("resultsByTime");
for (int i = 0; i < result.length(); i++) {
resultsByTime = result.getJSONObject(i);
total = resultsByTime.getJSONObject("total");
blendedCost = total.getJSONObject("BlendedCost");
usageQuantity = total.getJSONObject("UsageQuantity");
logger.info("blendedCost : " + blendedCost);
logger.info("usageQuantity : " + usageQuantity);
try {
blendedCostRootNode = objectMapper.readTree(blendedCost.toString());
usageQuantityRootNode = objectMapper.readTree(usageQuantity.toString());
} catch (IOException e) {
e.printStackTrace();
logger.error("Error", e);
}
cost = blendedCostRootNode.path("amount");
logger.info("Cost = " + cost);
totalCost = totalCost + cost.asDouble();
usage = usageQuantityRootNode.path("amount");
logger.info("Usage = " + usage);
totalRunningTime = totalRunningTime +usage.asDouble();
}
} catch (JSONException e) {
e.printStackTrace();
}
logger.info("Total Cost is : " +totalCost);
logger.info("Total Running time is : " +totalRunningTime);
listOfUsageAndCost.add(totalRunningTime.toString().replace("\"", ""));
listOfUsageAndCost.add(totalCost.toString().replace("\"", ""));
costAndUsage.put(instanceName, listOfUsageAndCost);
return costAndUsage;
}
Я сейчас пытаюсь сделать это через Python, используя документацию AWS, но я не уверен, как?
Документация AWS по Python показывает:
response = client.get_cost_and_usage(
TimePeriod={
'Start': 'string',
'End': 'string'
},
Granularity='DAILY'|'MONTHLY'|'HOURLY',
Filter={
'Or': [
{'... recursive ...'},
],
'And': [
{'... recursive ...'},
],
'Not': {'... recursive ...'},
'Dimensions': {
'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',
'Values': [
'string',
]
},
'Tags': {
'Key': 'string',
'Values': [
'string',
]
}
},
Metrics=[
'string',
],
GroupBy=[
{
'Type': 'DIMENSION'|'TAG',
'Key': 'string'
},
],
NextPageToken='string'
)
Я не понимаю, где мне следует передавать имена экземпляров или где передавать идентификатор экземпляра.Как я могу написать это правильно в формате Python, чтобы он вел себя так же, как мой код Java?