forked from tensult/aws-automation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstop_rds_instances.js
70 lines (65 loc) · 1.92 KB
/
stop_rds_instances.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
const AWS = require('aws-sdk')
// AWS.config.update({
// region: 'ap-south-1'
// })
const rds = new AWS.RDS();
async function getAllDbInstances() {
try {
let dbInstances = [];
let fetchPending = true;
let marker;
while (fetchPending) {
const params = {
Marker: marker,
};
const response = await rds.describeDBInstances(params).promise();
dbInstances = dbInstances.concat(response.DBInstances);
marker = response.Marker | undefined;
fetchPending = marker;
}
return dbInstances;
} catch (error) {
throw error;
}
}
async function getAllTagsOfRdsResource(resourceName) {
try {
const params = {
ResourceName: resourceName,
};
const response = await rds.listTagsForResource(params).promise();
return response.TagList;
} catch (error) {
throw error
}
}
function stopRdsInstance(instanceIdentifier) {
const params = {
DBInstanceIdentifier: instanceIdentifier
};
return rds.stopDBInstance(params).promise();
}
async function stopRdsInstancesByTag() {
try {
const dbInstances = await getAllDbInstances()
for (const instance of dbInstances) {
const tags = await getAllTagsOfRdsResource(instance.DBInstanceArn)
if (tags.find(o => o.Key.toLowerCase() === 'donotstop')) {
continue;
}
console.log('stoppable instance arn ', instance.DBInstanceArn);
const response = await stopRdsInstance(instance.DBInstanceIdentifier);
console.log('Stopped instance ', JSON.stringify(response, null, 2));
}
} catch (error) {
throw error
}
}
// stopRdsInstancesByTag()
exports.handler = async (event) => {
try {
await stopRdsInstancesByTag();
} catch (error) {
console.error(error);
}
}