Created
December 31, 2015 04:02
-
-
Save trentonstrong/c2b7b5925da07ca28db8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import urllib | |
import boto3 | |
import datetime | |
import json | |
import unittest | |
print('Loading function') | |
s3 = boto3.client('s3') | |
lambda_client = boto3.client('lambda') | |
def handler(event, context): | |
bucket = event['Records'][0]['s3']['bucket']['name'] | |
key = urllib.unquote_plus( | |
event['Records'][0]['s3']['object']['key']).decode('utf8') | |
version = event['Records'][0]['s3']['object']['versionId'] | |
# This is kind of jank, but hey! Maybe a good use case for S3 metadata in the future. | |
is_prod = key.endswith('_PROD.zip') | |
if not key.endswith('.zip'): | |
raise Exception('S3 objects must be zips!') | |
try: | |
deploy_function(bucket, key, version, is_prod) | |
return True | |
except Exception as e: | |
print(e) | |
print('Error getting object {} from bucket {}. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket)) | |
raise e | |
def deploy_function(bucket, key, version, publish, runtime='python2.7', role='', handler='handler.handler', timeout=60, memory_size=128): | |
name = key.replace('/', '_').replace('.zip', '') | |
description = ' - '.join([function_name, version]) | |
lambda_function = lambda_client.get_function(FunctionName=function_name) | |
if lambda_function is None: | |
lambda_client.create_function( | |
FunctionName=name, | |
Runtime=runtime, | |
Role=role, | |
Handler=handler, | |
Code={ | |
'S3Bucket': bucket, | |
'S3Key': key, | |
'S3ObjectVersion': version | |
}, | |
Description=description, | |
Timeout=timeout, | |
MemorySize=memory_size, | |
Publish=publish | |
) | |
else: | |
lambda_client.update_function_code( | |
FunctionName=name, | |
S3Bucket=bucket, | |
S3Key=key, | |
S3ObjectVersion=version, | |
Publish=publish | |
) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment