Skip to content

Instantly share code, notes, and snippets.

@otakky
Created September 7, 2016 00:59
Show Gist options
  • Save otakky/51e0e2b707972565a49cbbbf245a2553 to your computer and use it in GitHub Desktop.
Save otakky/51e0e2b707972565a49cbbbf245a2553 to your computer and use it in GitHub Desktop.
バックアップ用のAMIを取得する(lambda向け)
const AWS = require('aws-sdk');
AWS.config.region = 'ap-northeast-1';
AWS.config.setPromisesDependency(Promise);
const ec2 = new AWS.EC2();
exports.handler = function (evt, context, cb) {
if (!evt.date) {
return cb(new Error('please set "date" to a first argument.'));
}
ec2.describeTags({
Filters: [{
Name: "tag:backupDays",
Values: [evt.date + '']
}]
}).promise().then((data) => {
if (!data.Tags.length) { return []; }
const today = getToday();
const tasks = data.Tags.map((tag) => {
const id = tag.ResourceId;
return ec2.createImage({
InstanceId: id,
Name: `backup_for_${id}_${today}`,
Description: `backup for ${id} at ${today}`,
DryRun: false,
NoReboot: true,
}).promise();
});
return Promise.all(tasks);
}).then((amis) => {
const ids = amis.map((ami) => { return ami.ImageId; });
return ec2.createTags({
Resources: ids,
Tags: [
{
Key: 'isBackupByBatch',
Value: "true"
}
]
}).promise();
}).then((data) => {
cb(null, data);
}).catch(cb);
};
/**
* 現在の日付を返す
*
* @return {String} YYYY-M-D形式
*/
function getToday() {
const today = new Date();
return `${today.getYear() + 1900}-${today.getMonth() + 1}-${today.getDate()}`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment