Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
var AWS = require('aws-sdk');
var ec2 = new AWS.EC2({apiVersion: '2015-10-26'});
exports.handler = function(event, context) {
ec2.describeInstances({}, function(err, data) {
if (err) {
console.log(err, err.stack);
context.done('error', err.stack);
return;
}
var is_target = function(tags) {
for (var n in tags) {
if (tags[n].Key == 'Server' && tags[n].Value == 'bastion') {
return true;
}
}
return false;
};
var gips = [];
var get_target = function(ids, instances) {
for (var i = 0; i < instances.length; i++) {
var ins = instances[i];
if (is_target(ins.Tags)) {
if (ins.State.Name === 'running') {
console.log("running (instanceId: " + ins.InstanceId + "[" + ins.PublicIpAddress + "])");
gips.push(ins.PublicIpAddress);
} else {
console.log("starting (instanceId: " + ins.InstanceId + "])");
ids.push(ins.InstanceId);
}
}
}
};
var ids = [];
for (var i = 0; i < data.Reservations.length; i++) {
get_target(ids, data.Reservations[i].Instances);
}
if (ids.length === 0) {
context.done(null, {"ip": gips.join(','), "message": "no instance to start."});
return;
}
ec2.startInstances({InstanceIds: ids}, function(err, data) {
if (err) {
console.log(err, err.stack);
context.done('error', err.stack);
return;
}
console.log(data);
context.done(null, {"ip": gips.join(','), "message": "started instance(instanceId: " + ids.join(',') + ")"});
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment