Skip to content

Instantly share code, notes, and snippets.

@wata-gh
Created October 26, 2015 06:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wata-gh/22c7a01e5b826957124c to your computer and use it in GitHub Desktop.
Save wata-gh/22c7a01e5b826957124c to your computer and use it in GitHub Desktop.
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