Skip to content
This repository has been archived by the owner on Feb 9, 2019. It is now read-only.

Timezone support #7

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,33 @@ Source code for the AWS solution "EC2 Scheduler".

- code/ec2-scheduler.py

## Building

In order to build this, you will need some python libraries and create a zip file to upload to Lambda / Cloudformation.

Basic instructions are:
cd code
pip install boto3 -t .
pip install urllib -t .
pip install datetime -t .
pip install pytz -t .
zip -r ../ec2-scheduler.zip

### Lambda without cloudformation
If you want to upload directly to Lambda, replace the code that reads the DynamoDB table from cloudformation with:
IE: replace

outputs = {}
stack_name = context.invoked_function_arn.split(':')[6].rsplit('-', 2)[0]
response = cf.describe_stacks(StackName=stack_name)
for e in response['Stacks'][0]['Outputs']:
outputs[e['OutputKey']] = e['OutputValue']
ddbTableName = outputs['DDBTableName']

with:

ddbTableName = 'EC2-Scheduler'

***

Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Expand Down
27 changes: 20 additions & 7 deletions code/ec2-scheduler.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
import boto3
import datetime
import json
import calendar
from pytz import timezone
from urllib2 import Request
from urllib2 import urlopen
from collections import Counter
Expand Down Expand Up @@ -75,8 +77,8 @@ def lambda_handler(event, context):
sendData = str(item['SendAnonymousData']).lower()
createMetrics = str(item['CloudWatchMetrics']).lower()
UUID = str(item['UUID'])
TimeNow = datetime.datetime.utcnow().isoformat()
TimeStamp = str(TimeNow)
TimeNow = datetime.datetime.now(timezone('UTC'))
TimeStamp = str(TimeNow.replace(tzinfo=None).isoformat())

# Declare Dicts
regionDict = {}
Expand All @@ -90,10 +92,6 @@ def lambda_handler(event, context):
ec2 = boto3.resource('ec2', region_name=region['RegionName'])

awsregion = region['RegionName']
now = datetime.datetime.now().strftime("%H%M")
nowMax = datetime.datetime.now() - datetime.timedelta(minutes=59)
nowMax = nowMax.strftime("%H%M")
nowDay = datetime.datetime.today().strftime("%a").lower()

# Declare Lists
startList = []
Expand Down Expand Up @@ -140,11 +138,26 @@ def lambda_handler(event, context):
if len(ptag) >= 2:
stopTime = ptag[1]
if len(ptag) >= 3:
timeZone = ptag[2].lower()
timeZone = ptag[2]
if len(ptag) >= 4:
daysActive = ptag[3].lower()

isActiveDay = False
print ("Timezone: ", timeZone)
# Calculate per ec2 tag, because timezone can be different
try:
localtz = timezone(timeZone)
print ("Timezone OK")
except:
localtz = timezone(defaultTimeZone)
print ("Timezone REJECTED, defaulting to UTC. Valid timezones are pytz timezones. Please pick from the list below:")
for tz in pytz.all_timezones:
print tz

now = TimeNow.astimezone(localtz).strftime("%H%M")
nowMax = TimeNow.astimezone(localtz) - datetime.timedelta(minutes=59)
nowMax = nowMax.strftime("%H%M")
nowDay = calendar.day_abbr[TimeNow.astimezone(localtz).weekday()].lower()

# Days Interpreter
if daysActive == "all":
Expand Down