-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.mjs
60 lines (51 loc) · 2.3 KB
/
index.mjs
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
import { ECSClient, UpdateServiceCommand } from '@aws-sdk/client-ecs';
import { EC2Client, StartInstancesCommand, StopInstancesCommand } from '@aws-sdk/client-ec2';
const ecsClient = new ECSClient({ region: process.env.AWS_REGION || 'ap-south-1' });
const ec2Client = new EC2Client({ region: process.env.AWS_REGION || 'ap-south-1' });
/*
ecs =>
{
"cluster": "divamtech-staging",
"services": ["divamtech-staging-server-service", "divamtech-staging-worker-service"],
"desiredCount": 1
}
ec2 => { "ec2InstanceIds": ["i-0362c8fc8eb38bc36"], "ec2Action": "start" }
*/
export const handler = async (event) => {
try {
console.log('event', event);
// Handling ECS services
if (event?.cluster) {
if (!event?.services || event?.services?.length === 0) {
throw Error(`ECS ${event.services} services are not provided.`);
}
const desiredCount = event?.desiredCount || 0;
for (let i = 0; i < event.services.length; i++) {
const service = event.services[i];
const payload = { cluster: event.cluster, service, desiredCount };
await ecsClient.send(new UpdateServiceCommand(payload));
}
const serviceState = desiredCount > 0 ? 'started' : 'stopped';
const body = `${event.cluster} cluster::${event.services} services have been ${serviceState}`;
console.log(body);
} else if (event?.ec2InstanceIds && event?.ec2InstanceIds.length > 0) {
// Handling EC2 instances
const ec2InstanceIds = event.ec2InstanceIds;
const ec2Action = event.ec2Action || 'stop'; // default to stop if not provided
const ec2Params = { InstanceIds: ec2InstanceIds };
if (ec2Action === 'start') {
await ec2Client.send(new StartInstancesCommand(ec2Params));
console.log(`EC2 instances ${ec2InstanceIds} have been started.`);
} else if (ec2Action === 'stop') {
await ec2Client.send(new StopInstancesCommand(ec2Params));
console.log(`EC2 instances ${ec2InstanceIds} have been stopped.`);
} else {
throw Error(`Invalid EC2 action: ${ec2Action}. Allowed actions are 'start' and 'stop'.`);
}
}
return { statusCode: 200, body: 'Request processed successfully' };
} catch (error) {
console.error('Error:', error, event);
return { statusCode: 500, body: 'Error processing request' };
}
};