Skip to content

Instantly share code, notes, and snippets.

@alexcheng1982
Created December 19, 2017 20:02
Show Gist options
  • Save alexcheng1982/1973b3a158a71f0804b8587eef6b35ca to your computer and use it in GitHub Desktop.
Save alexcheng1982/1973b3a158a71f0804b8587eef6b35ca to your computer and use it in GitHub Desktop.
AWS Lambda check instances
function findTag(tags, key) {
for (var i = tags.length - 1; i >= 0; i--) {
if (tags[i].Key === key) {
return tags[i].Value;
}
}
}
exports.handler = (event, context, callback) => {
var AWS = require('aws-sdk');
var ec2 = new AWS.EC2();
var params = {
DryRun: false,
Filters: [
{
Name: 'tag:managed_by',
Values: [
'ansible'
],
},
{
Name: 'instance-state-code',
Values: [
'16',
]
}
]
};
ec2.describeInstances(params, function (err, data) {
if (err) {
context.fail(err);
} else {
var instancesToTerminate = [];
var instancesToUpdate = [];
var response = [];
if (data.Reservations && data.Reservations.length > 0) {
for (var i = data.Reservations.length - 1; i >= 0; i--) {
var instances = data.Reservations[i].Instances;
if (instances && instances.length > 0) {
for (var j = instances.length - 1; j >= 0; j--) {
var instance = instances[j];
var ttl = parseInt(findTag(instance.Tags, 'ttl'), 10);
if (ttl <= 0) {
instancesToTerminate.push(instance.InstanceId);
} else {
instancesToUpdate.push({
id: instance.InstanceId,
ttl: ttl
});
}
}
}
}
}
if (instancesToTerminate.length > 0) {
var params = {
InstanceIds: instancesToTerminate,
DryRun: false,
};
ec2.terminateInstances(params, function(err, data) {
if (err) {
console.log(err, err.stack);
context.fail(err);
} else {
context.succeed("Terminated instances: " + instancesToTerminate);
}
});
}
else {
var tasksNum = instancesToUpdate.length;
response.push('No instances to terminate');
for (var i = instancesToUpdate.length - 1; i >= 0; i--) {
var toUpdate = instancesToUpdate[i];
function doUpdate(toUpdate) {
ec2.createTags({
Resources: [
toUpdate.id
],
Tags: [
{
Key: 'ttl',
Value: (toUpdate.ttl - 1) + ''
}
]
}, function(err, data) {
tasksNum--;
if (err) {
console.log(err, err.stack);
context.fail(err);
} else {
response.push('Updated ttl of ' + toUpdate.id + ' to ' + (ttl - 5));
}
if (tasksNum <= 0) {
context.succeed(response.join(', '));
}
});
}
doUpdate(toUpdate);
}
}
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment