-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
59 lines (48 loc) · 1.6 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
const aws = require('aws-sdk')
const ec2 = new aws.EC2()
const runModeTagKey = 'RunMode'
const alwaysOnTagValue = 'AlwaysOn'
const getRunningInstances = async _ => {
const describeInstancesResult = await ec2.describeInstances({
Filters: [
{
Name: 'instance-state-name',
Values: ['running']
}
]
}).promise()
return describeInstancesResult.Reservations.map(r => {
return r.Instances.flat()
}).flat()
}
const filterOnDemandInstances = instances => {
return instances.filter(instance => {
const tags = instance.Tags
const runModeTag = tags.find(t => t.Key === runModeTagKey)
if (runModeTag) {
return runModeTag.Value !== alwaysOnTagValue
} else {
return true
}
})
}
const stopInstances = async instances => {
const stopInstancesResult = await ec2.stopInstances({
InstanceIds: instances.map(i => i.InstanceId)
}).promise()
return stopInstancesResult.StoppingInstances.map(i => {
return i.InstanceId
})
}
exports.handler = async _ => {
const runningInstances = await getRunningInstances()
const onDemandInstances = filterOnDemandInstances(runningInstances)
if (onDemandInstances.length === 0) {
const message = 'No OnDemand instance running.'
console.log(message)
return message
}
const stoppedInstances = await stopInstances(onDemandInstances)
console.log(stoppedInstances)
return stoppedInstances
}