forked from ThomasTusche/ecs-scaling-scheduler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlambda_function.py
71 lines (53 loc) · 1.95 KB
/
lambda_function.py
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
import json
import boto3
def lambda_handler(event, context):
### The cloudwatch alarm sends a paramater called 'action' which is set to 'start' or 'stop'
### Lambda decides depending on the value whether to start or stop the container
cloudwatchvalue = event.get('action')
### The cloudwatch alarm sends a paramater called 'cluster' which contains the ecs cluster name
clusterName = event.get('cluster')
client = boto3.client('ecs')
### Query to the ECS API to get all running services
### Output limit is currently set to 50
try:
response = client.list_services(
cluster=clusterName,
maxResults=50,
launchType='FARGATE',
schedulingStrategy='REPLICA'
)
except:
print("didnt worked")
### Retrieves only the plain service arns from the output
### Values are stored in a list
servicelist = response['serviceArns']
print(servicelist)
print(cloudwatchvalue)
if 'start' == cloudwatchvalue:
spawncontainer(servicelist,clusterName)
elif 'stop' == cloudwatchvalue:
stopcontainer(servicelist,clusterName)
return {
'statusCode': 200,
'body': json.dumps('Script finished')
}
### Sets the desired count of tasks per service to 1
### Container will spawn after a few moments
def spawncontainer(servicearns,clusterName):
client = boto3.client('ecs')
for srv in servicearns:
responseUpdate = client.update_service(
cluster=clusterName,
service=srv,
desiredCount=1,
)
### Sets the desired count of tasks per service to 0
### Services still runs but without any container
def stopcontainer(servicearns,clusterName):
client = boto3.client('ecs')
for srv in servicearns:
responseUpdate = client.update_service(
cluster=clusterName,
service=srv,
desiredCount=0,
)