-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathindex.js
58 lines (51 loc) · 1.29 KB
/
index.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
'use strict';
/**
* AWS Lambda function that stops servers.
*
* @author Sam Verschueren <[email protected]>
* @since 09 Oct. 2015
*/
// module dependencies
var AWS = require('aws-sdk');
var pify = require('pify');
var Promise = require('pinkie-promise');
var ec2 = new AWS.EC2();
/**
* The handler function.
*
* @param {object} event The data regarding the event.
* @param {object} context The AWS Lambda execution context.
*/
exports.handler = function (event, context) {
var describeParams = {
Filters: [
{
Name: 'tag:StopGroup',
Values: [
context.functionName
]
}
]
};
// Describe the instances
pify(ec2.describeInstances.bind(ec2), Promise)(describeParams)
.then(function (data) {
var stopParams = {
InstanceIds: []
};
data.Reservations.forEach(function (reservation) {
reservation.Instances.forEach(function (instance) {
if (instance.State.Code === 16) {
// 0: pending, 16: running, 32: shutting-down, 48: terminated, 64: stopping, 80: stopped
stopParams.InstanceIds.push(instance.InstanceId);
}
});
});
if (stopParams.InstanceIds.length > 0) {
// Stop the instances
return pify(ec2.stopInstances.bind(ec2), Promise)(stopParams);
}
})
.then(context.succeed)
.catch(context.fail);
};