Created
September 7, 2016 01:00
-
-
Save otakky/32348c20b88b52a14b681f47b52a5f08 to your computer and use it in GitHub Desktop.
特定のタグがついたAMIが、作成日から30日経過してたら削除する(lambda向け)
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
const AWS = require('aws-sdk'); | |
AWS.config.region = 'ap-northeast-1'; | |
AWS.config.setPromisesDependency(Promise); | |
const ec2 = new AWS.EC2(); | |
const BACKUP_DAYS = 30; | |
exports.handler = function (evt, context, cb) { | |
ec2.describeImages({ | |
Filters: [{ | |
Name: 'tag:isBackupByBatch', | |
Values: ['true'] | |
}] | |
}).promise().then((data) => { | |
const images = getBackupTargetAmis(data.Images); | |
const tasks = images.map((image) => { | |
return ec2.deregisterImage({ | |
ImageId: image.ImageId, | |
DryRun: false | |
}).promise(); | |
}); | |
return Promise.all(tasks); | |
}).then((data) => { | |
cb(null, data); | |
}).catch((err) => { | |
cb(err); | |
}); | |
}; | |
/** | |
* AMIを取得してから一定以上の日数が経過したイメージをフィルタし、 | |
* IDだけにして返す | |
* | |
* @param {Array.<Object>} images descriveImagesの返り値 | |
* @return {Array.<Object>} フィルタ後のimages | |
*/ | |
function getBackupTargetAmis(images) { | |
const nowTime = new Date().getTime(); | |
return images.filter((image) => { | |
const backupTime = new Date(image.CreationDate).getTime(); | |
const pastDate = (nowTime - backupTime) / (1000 * 60 * 60 * 24); | |
return (BACKUP_DAYS < pastDate); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment