-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstar-stop-instances.py
92 lines (80 loc) · 2.61 KB
/
star-stop-instances.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import boto3
from datetime import datetime, date, time
from dateutil import tz
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def getInstancesFromTags(tagKey,tagValue,state):
client = boto3.client('ec2')
instDict=client.describe_instances(Filters=[{'Name': 'instance-state-name', 'Values': [state]},{'Name': 'tag:'+tagKey, 'Values': [tagValue]}])
instances=[]
for r in instDict['Reservations']:
for inst in r['Instances']:
instances.append(inst)
return instances
def buildMessageForSQS(action,instances):
message = "{"
message = message + "'Action': '"+action+"',"
message = message + "'instances' : "+str(instances)+ "}"
logger.info(message)
sendToSQS(message)
def sendToSQS(message):
client = boto3.client('sqs')
response = client.send_message(
QueueUrl='https://sqs.eu-west-1.amazonaws.com/648292630089/sw-aws-scheduled-instances',
MessageBody= message
)
def handler(event, context):
startHour=8
stopHour=20
dyna = boto3.client('dynamodb')
dbresponse = dyna.scan(
TableName='office_hours',
Select='ALL_ATTRIBUTES'
)
for name in dbresponse['Items']:
if name['name']['S']=='start':
startHour=int(name['time']['N'])
elif name['name']['S']=='stop':
stopHour=int(name['time']['N'])
client = boto3.client('ec2')
stopped='stopped'
running='running'
tagKey = 'Schedule'
tagValue='office_hours'
if 'tagValue' in event:
tagValue = event['tagValue']
parisTimeZone = tz.gettz('Europe/Paris')
nowDate=datetime.now(parisTimeZone)
currentHour = int(nowDate.hour)
officeHours=False
if currentHour >= startHour and currentHour < stopHour and int(nowDate.weekday())<5:
officeHours=True
instancesToStart=[]
instancesToStop=[]
if officeHours:
instancesToStart.extend(getInstancesFromTags('Schedule','office_hours',stopped))
else:
instancesToStop.extend(getInstancesFromTags('Schedule','office_hours',running))
instancesToStart.extend(getInstancesFromTags('Schedule','always',stopped))
if not instancesToStart:
logger.info('No instances to start!')
else:
hostIds=[]
for inst in instancesToStart:
hostIds.append(inst['InstanceId'])
logger.info('Starting instances with ids: {}'.format(str(hostIds)))
client.start_instances(InstanceIds=hostIds)
buildMessageForSQS('Started',instancesToStart)
if not instancesToStop:
logger.info('No instances to stop!')
else:
hostIds=[]
for inst in instancesToStop:
hostIds.append(inst['InstanceId'])
logger.info('Stopping instances with ids: {}'.format(str(hostIds)))
client.stop_instances(InstanceIds=hostIds)
buildMessageForSQS('Stopped',instancesToStop)
return{
'message' : "Trigger function finished"
}