Last active
August 29, 2015 14:26
-
-
Save tzach/c6f0548eecae18508259 to your computer and use it in GitHub Desktop.
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
console.log('Loading function'); | |
var aws = require('aws-sdk'); | |
var region = 'us-west-2'; | |
var ec2 = new aws.EC2({region: region}); | |
var topicArn = "arn:aws:sns:us-west-2:797456418907:cloudius_running_ec2_instances"; | |
function push(payload, context) { | |
var sns = new aws.SNS(); | |
var params = { | |
Message: payload, | |
Subject: "EC2 running instancs", | |
TopicArn: topicArn | |
}; | |
sns.publish(params, | |
function(err, data) { | |
if (err) { | |
console.info("error:", err.stack); | |
context.fail(null, err); | |
} | |
else { | |
console.info('message published to SNS'); | |
context.succeed("message published to SNS"); | |
} | |
}); | |
} | |
function extract_data(data, context) { | |
count = data.Reservations.length; | |
if (count === 0) { | |
context.done(null, "No running instances"); | |
} | |
else { | |
var atts = {}; | |
atts.default = "You have running EC2 instances"; | |
data.Reservations.map(function(r) { | |
r.Instances.map(function(i) { | |
id = i.InstanceId; | |
atts[id] = {}; | |
atts[id].PublicIpAddress = i.PublicIpAddress; | |
atts[id].keyName = i.KeyName; | |
atts[id].LaunchTime = i.LaunchTime; | |
atts[id].InstanceType = i.InstanceType; | |
console.log(atts[id]); | |
}); | |
}); | |
push(JSON.stringify(atts,null,'\t'), context); | |
} | |
} | |
exports.handler = function(event, context) { | |
console.log("nLoading handler"); | |
var msg = JSON.parse(event.Records[0].Sns.Message); | |
console.log("msg:", msg); | |
if (msg.type != "chime") { | |
context.succeed("not a chime event"); | |
return; | |
} | |
if (msg.minute != "00") { | |
context.succeed("not the top of the hour"); | |
return; | |
} | |
ec2.describeInstances( | |
{Filters: | |
[{Name: "instance-state-name", Values: ["running"]}]}, | |
function(err, data) { | |
if (err) context.fail(null, err); | |
else { | |
console.log("successful response from EC2"); | |
extract_data(data, context); | |
} | |
}); | |
}; | |
// use the following IAM (or more limited) | |
{ | |
"Statement": [ | |
{ | |
"Action": [ | |
"logs:CreateLogGroup", | |
"logs:CreateLogStream", | |
"logs:PutLogEvents" | |
], | |
"Effect": "Allow", | |
"Resource": "arn:aws:logs:*:*:*" | |
}, | |
{ | |
"Effect": "Allow", | |
"Action": [ | |
"ec2:*", | |
"sns:*" | |
], | |
"Resource": "*" | |
} | |
] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment