i want to build a small app that reads the AWS CPU USAGE every 5 minutes lets say, i built the params, call the getMetricsStatistics but it keeps returning me an empty array, you know why? this is the code:
const aws = require('aws-sdk')
const dotenv = require('dotenv').config()
aws.config.setPromisesDependency()
aws.config.update({
accessKeyId: process.env.EC2_ACCESS_KEY,
secretAccessKey: process.env.EC2_SECRET_KEY,
region: 'us-east-1',
})
const s3 = new aws.CloudWatch()
var params = {
EndTime: new Date() /* required */,
/* required */
MetricName: 'EngineCPUUtilization',
Namespace: 'AWS/S3',
StartTime: new Date('Mon Dec 6 2021') /* required */,
/* required */
Dimensions: [
{
Name: 'Per-Instance Metrics' /* required */,
Value: 'i-abbc12a7' /* required */,
},
{
Name: 'StorageType',
Value: 'AllStorageTypes',
},
/* more items */
],
Period: 300 /* required */,
Statistics: ['Average'] /* required */,
}
async function asyncMethod() {
return await s3.getMetricStatistics(params, function (err, data) {
if (err) console.log(err, err.stack)
// an error occurred
else {
console.log(data)
}
}) // successful response
}
const d = asyncMethod()
response is always empty array in the data.Datapoints.
PS, how do i get the names of all of my buckets? thanks!
First problem is that you're calling an async method, "asyncMethod," and you're not waiting for it to finish (resolve the promise). Your asnycMethod is also somewhat redundant and over complicated. I would remove all of that and change that to 1) use the .promise() form of the SDK call, and 2) use the thenable promise approach which is simpler for what you're trying to do:
s3.getMetricStatistics(params).promise()
.then(d => {
console.log(data)
/* do stuff with d here */
})
.catch(err => {
console.log(err);
});
Additionally, you can't set d to the result like you're trying to do because the promise will be returned as d, not the result of the callback data value. You can't do an await on asyncMethod call either because you're not in an async function. Additionally, you are not actually returning a value from the callback.
That said, I do not see anything specifically wrong with the general call you're making to the AWS SDK, but I would check the Dimensions you're sending for accurate settings. I assume that you're sure that the stats you're looking for are actually there for the time period specified.