-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
56 lines (49 loc) · 1.26 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
'use strict';
/**
* AWS Lambda function that stop/start aws servers
* @author Amr Reda <amrreda@outlook.com>
* @since 30 Jul. 2017
*/
// module dependencies
const AWS = require('aws-sdk');
const pify = require('pify');
const Promise = require('pinkie-promise');
const 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) {
const describeParams = {
Filters: [
{
Name: 'tag:DevServer',
Values: [
context.functionName
]
}
]
};
// Describe the instances
pify(ec2.describeInstances.bind(ec2), Promise)(describeParams)
.then(data => {
const stopParams = {
InstanceIds: []
};
data.Reservations.forEach(reservation => {
reservation.Instances.forEach(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);
};