Skip to content

Instantly share code, notes, and snippets.

@made2591
Created March 24, 2018 14:41
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save made2591/acc61010fa119929718e122ca69d8a92 to your computer and use it in GitHub Desktop.
Save made2591/acc61010fa119929718e122ca69d8a92 to your computer and use it in GitHub Desktop.
AWS Lambda Node.js to get change of status in EC2 instances.
const Slack = require("slack-node");
// Load the AWS SDK for Node.js
const AWS = require("aws-sdk");
// Set the region
AWS.config.update({region: process.env.REGION});
// Create EC2 service object
var ec2 = new AWS.EC2();
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
function checkDNS(dns) {
if (dns != "") return dns;
return "Not available until restart"
}
function composeMsg(infos) {
var payload = {
channel: process.env.SLACK_CHANNEL,
username: process.env.SLACK_BOT_NAME,
text: "EC2 Instances status in "+process.env.REGION,
attachments: [{
color: "#36a64f",
text: "Details",
fields: [],
image_url: "🏢",
thumb_url: "🏢"
}]
};
infos.forEach(function(info, index) {
payload['attachments'][0]['fields'].push({
"title": "💻 "+capitalizeFirstLetter(info['name'])+" is "+info["status"],
"value": "ID: "+info['id']+"; Public DNS: "+checkDNS(info["dns"])+";",
"short": true
});
});
return payload;
}
function slackNotifier(infos) {
var payload = composeMsg(infos);
var webhookUri = process.env.SLACK_WEBHOOK;
var slack = new Slack();
slack.setWebhook(webhookUri);
slack.webhook(payload, function(err, response) {
if (err) {
console.log(err);
}
});
return payload;
}
exports.handler = (event, context, callback) => {
var params = {};
ec2.describeInstances(params, function(err, data) {
if (err) {
console.log(err, err.stack);
}
else {
var count = 0;
var infos = [];
data = JSON.parse(JSON.stringify(data));
// for each instance
for (var reservartion of data["Reservations"]) {
var instance = reservartion["Instances"][0];
infos.push({});
// find id
infos[count]["id"] = instance["InstanceId"];
// find name
for (var tag of instance["Tags"]) {
if (tag["Key"] == "Name") {
infos[count]["name"] = tag["Value"];
break;
}
}
// save status
infos[count]["status"] = instance["State"]["Name"];
// save dns and ip
infos[count]["dns"] = instance["PublicDnsName"];
infos[count]["ip"] = instance["PublicIpAddress"];
count = count + 1;
}
console.log(infos);
// send message
var msg = slackNotifier(infos);
callback(null, msg);
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment