forked from geekmuse/iot-button-ec2-controller
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
73 lines (67 loc) · 2.82 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
var AWS = require('aws-sdk');
AWS.config.update({region: 'us-east-1'});
var _ = require('underscore');
var ec2 = new AWS.EC2({ apiVersion: '2016-11-15' });
exports.handler = (event, context, callback) => {
console.log('Received event:', event);
var r;
var i;
var instanceIds = [];
var params = {
Filters: [{
Name: 'tag-key',
Values: [
'IoT Enabled'
]
},
]
};
ec2.describeInstances(params, function(err, data) {
if (err) {
console.log(err, err.stack); // an error occurred
context.fail('Error occurred. Aborting.');
return;
}
if (data.Reservations.length > 0) {
for (r in data.Reservations) {
if (data.Reservations[r].Instances.length > 0) {
for (i in data.Reservations[r].Instances) {
if (event.clickType === 'SINGLE') {
if (_.contains(['stopped'], data.Reservations[r].Instances[i].State.Name)) {
instanceIds.push(data.Reservations[r].Instances[i].InstanceId);
}
} else if (event.clickType === 'DOUBLE') {
if (_.contains(['running'], data.Reservations[r].Instances[i].State.Name)) {
instanceIds.push(data.Reservations[r].Instances[i].InstanceId);
}
}
}
}
}
}
i = '';
if (instanceIds.length > 0) {
if (event.clickType === 'SINGLE') {
ec2.startInstances({ InstanceIds: instanceIds }, function(err, data) {
if (!err) {
context.succeed({'msg': 'All affected instances started successfully.', 'instanceIds': instanceIds});
} else {
console.log(err, err.stack);
context.fail({'msg': 'Instances failed to start.', 'instanceIds': instanceIds});
}
});
} else if (event.clickType === 'DOUBLE') {
ec2.stopInstances({ InstanceIds: instanceIds }, function(err, data) {
if (!err) {
context.succeed({'msg': 'All affected instances stopped successfully.', 'instanceIds': instanceIds});
} else {
console.log(err, err.stack);
context.fail({'msg': 'Instances failed to stop.', 'instanceIds': instanceIds});
}
});
}
} else {
context.succeed({'msg': 'No instances in a state to be affected by this operation.', 'instanceIds': instanceIds});
}
});
};