Skip to content

Instantly share code, notes, and snippets.

@wata-gh
Created October 10, 2015 10:19
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/f8292b79ebd68b8b98e8 to your computer and use it in GitHub Desktop.
Save wata-gh/f8292b79ebd68b8b98e8 to your computer and use it in GitHub Desktop.
var AWS = require('aws-sdk');
var ec2 = new AWS.EC2({
apiVersion: '2015-10-10',
accessKeyId: '',
secretAccessKey: '',
region: 'ap-northeast-1'
});
exports.handler = function(event, context) {
ec2.describeInstances({
Filters: [{
Name: 'instance-state-name',
Values: ['running']
}]
}, 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) {
// don't stop if OperatingTime tag is Full
if (tags[n].Key == 'OperatingTime' && tags[n].Value == 'Full') {
return false;
}
}
return true;
};
var get_target = function(ids, instances) {
for (var i = 0; i < instances.length; i++) {
var ins = instances[i];
if (is_target(ins.Tags)) {
console.log("stopping (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);
}
ec2.stopInstances({InstanceIds: ids}, function(err, data) {
if (err) {
console.log(err, err.stack);
context.done('error', err.stack);
return;
}
console.log(data);
context.done(null, '');
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment