Last active
May 8, 2018 14:55
-
-
Save fujiwara/3c3ff97d86a66f649ca82e188e43aa23 to your computer and use it in GitHub Desktop.
AWS billing post to SNS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const aws = require('aws-sdk'); | |
const cw = new aws.CloudWatch({region: 'us-east-1'}); | |
const sns = new aws.SNS(); | |
exports.handler = (event) => { | |
const endTime = new Date(); | |
const startTime = new Date(); | |
startTime.setDate(endTime.getDate() - 2); // 2 days ago | |
const param = { | |
MetricName: 'EstimatedCharges', | |
Namespace: 'AWS/Billing', | |
Period: 86400, | |
StartTime: startTime, | |
EndTime: endTime, | |
Statistics: ['Maximum'], | |
Dimensions: [ | |
{ | |
Name: 'Currency', | |
Value: 'USD' | |
} | |
] | |
}; | |
cw.getMetricStatistics(param, (err, data) => { | |
console.log(err, data); | |
if (err) { | |
console.log(err); | |
return; | |
} | |
const dp = data["Datapoints"].sort((a, b) => { | |
return (a.Timestamp < b.Timestamp) ? 1 : -1; | |
}); | |
const prev = dp[0]["Maximum"]; | |
const curr = dp[1]["Maximum"]; | |
const diff = curr > prev ? Math.round((curr - prev)*100)/100 : curr; | |
const name = process.env.ACCOUNT_NAME || ""; | |
const subject = `${name} Billing estimated charges ${curr} (+${diff}) USD at ${endTime.toISOString()}`; | |
console.log(subject); | |
const params = { | |
Subject: subject, | |
Message: JSON.stringify(data), | |
TopicArn: process.env.SNS_TOPIC_ARN, | |
}; | |
sns.publish(params, (err, data) => { | |
if (err) { | |
console.log(err); | |
} else { | |
console.log("success publish to SNS topic"); | |
} | |
}); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment