-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathautomated_ec2_snapshots.js
93 lines (83 loc) · 2.6 KB
/
automated_ec2_snapshots.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#!/usr/bin/env node
var aws = require('aws-sdk');
var _ = require('underscore');
var moment = require('moment');
var winston = require('winston');
winston.remove(winston.transports.Console);
winston.add(winston.transports.File, { filename: '/var/tmp/automated_ami_snapshots.log' });
aws.config.update({
region: 'us-east-1',
//logger: process.stdout
})
var now = moment().format("YYYY-MM-DD-HH");
winston.info('START')
var ec2 = new aws.EC2();
var instances = [
{
name: 'slice-dwh-poc-admin-002',
id: 'i-6a969cf2',
frequency: 'daily',
keep_days: '14'
}
]
//winston.info (instances)
function delete_ami_snapshot(image_id) {
// delete image
var params = { ImageId: image_id, DryRun: false };
ec2.deregisterImage(
params,
function(err, data) {
if (err) winston.info(err, err.stack);
else { winston.info(data); }
}
);
}
function create_ami_snapshot(id, name) {
var params = { InstanceId: id, Name: name + '_' + now, DryRun: false, NoReboot: true };
ec2.createImage(
params,
function(err, data) {
if (err) {
winston.info(err, err.stack);
}
else { winston.info(data); }
}
)
}
_.each(
instances,
function (inst) {
var params = {
DryRun: false,
Filters: [ {Name: 'name', Values: [ inst.name + '_*' ] } ]
};
daily_done = false
ec2.describeImages(
params,
function(err, data) {
if (err) winston.info(err, err.stack);
else {
_.each(
data.Images,
function (image) {
if ( moment(image.CreationDate).isAfter(moment().subtract(1, 'days')) ) {
daily_done = true
winston.info('Found daily backup: ', moment(image.CreationDate).format('YYYY-MM-DD HH:mm'))
}
var expired = moment(image.CreationDate).isBefore(moment().subtract(inst.keep_days, 'days'))
if ( expired ) {
// delete image
delete_ami_snapshot(image.ImageId)
}
}
)
//winston.info(images)
}
// do backup
if ( daily_done == false) {
create_ami_snapshot(inst.id, inst.name)
}
}
);
}
)