Created
December 7, 2016 10:19
-
-
Save manuquentin/adee523b60a4723e9e4819ea69713ab6 to your computer and use it in GitHub Desktop.
Lambda used to trash untagged instances via CloudTrail and CloudWatch
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
'use strict'; | |
// WARN : works only for 1 instance at time, we have to call describeTags for each instance | |
const zlib = require('zlib'); | |
const AWS = require('aws-sdk'); | |
const ec2 = new AWS.EC2(); | |
exports.handler = (event, context, callback) => { | |
const payload = new Buffer(event.awslogs.data, 'base64'); | |
zlib.gunzip(payload, (err, res) => { | |
if (err) return callback(err); | |
const payload = JSON.parse(res.toString('utf8')); | |
const instanceIds = payload.logEvents | |
.map(e => JSON.parse(e.message)) | |
.filter(m => m.eventName == 'RunInstances') | |
.map(e => e.responseElements.instancesSet.items[0].instanceId); | |
console.log('instanceIds', instanceIds); | |
if(instanceIds.length === 0) return callback(null, 'No instance started'); | |
ec2.describeTags({ Filters: [ { Name: "resource-id", Values: instanceIds } ]}, (err, data) => { | |
if (err) return callback(err); | |
if (data.Tags.length === 0) { | |
console.log('terminating', instanceIds); | |
return ec2.terminateInstances({ InstanceIds: instanceIds }, callback); | |
} | |
callback(null, 'Nothing to stop'); | |
}); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment