|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const AWS = require('aws-sdk'); |
| 4 | +const _ = require('lodash'); |
| 5 | + |
| 6 | +const EC2 = new AWS.EC2(); |
| 7 | +const AutoScaling = new AWS.AutoScaling(); |
| 8 | + |
| 9 | +module.exports = function () { |
| 10 | + return Promise.all([rotatedImages(), usedImageIds()]) |
| 11 | + .then(_.spread((rotatedImages, usedImageIds) => { |
| 12 | + return _.reject(rotatedImages, image => { |
| 13 | + return _.includes(usedImageIds, image.ImageId); |
| 14 | + }); |
| 15 | + })) |
| 16 | + .then(images => { |
| 17 | + const promises = images.map(image => { |
| 18 | + return deregisterImage(image) |
| 19 | + .then(deleteSnapShot) |
| 20 | + }); |
| 21 | + return Promise.all(promises); |
| 22 | + }); |
| 23 | +}; |
| 24 | + |
| 25 | +function rotatedImages() { |
| 26 | + return EC2.describeImages({ |
| 27 | + Filters: [ |
| 28 | + { |
| 29 | + Name: 'tag:Rotated', |
| 30 | + Values: ['true'], |
| 31 | + }, |
| 32 | + ], |
| 33 | + }).promise() |
| 34 | + .then(data => data.Images); |
| 35 | +} |
| 36 | + |
| 37 | +function usedImageIds() { |
| 38 | + return AutoScaling.describeLaunchConfigurations({}).promise() |
| 39 | + .then(data => { |
| 40 | + return data.LaunchConfigurations.map(lc => lc.ImageId); |
| 41 | + }); |
| 42 | +} |
| 43 | + |
| 44 | +function deregisterImage(image) { |
| 45 | + return EC2.deregisterImage({ |
| 46 | + ImageId: image.ImageId, |
| 47 | + }).promise() |
| 48 | + .then(() => { |
| 49 | + console.log(`deregistered ${image.ImageId}`); |
| 50 | + return image; |
| 51 | + }) |
| 52 | + // ignore error and continue |
| 53 | + .catch(() => image) |
| 54 | +} |
| 55 | + |
| 56 | +function deleteSnapShot(image) { |
| 57 | + const snapShotId = _.chain(image.BlockDeviceMappings) |
| 58 | + .flatten() |
| 59 | + .map(m => m.Ebs) |
| 60 | + .compact() |
| 61 | + .map(m => m.SnapshotId) |
| 62 | + .first() |
| 63 | + .value(); |
| 64 | + |
| 65 | + return EC2.deleteSnapshot({ |
| 66 | + SnapshotId: snapShotId, |
| 67 | + }).promise() |
| 68 | + .then(() => { |
| 69 | + console.log(`deleted ${snapShotId}`); |
| 70 | + return image; |
| 71 | + }) |
| 72 | + .catch(() => image) |
| 73 | +} |
| 74 | + |
0 commit comments