Created
October 10, 2015 10:19
-
-
Save wata-gh/f8292b79ebd68b8b98e8 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
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