-
-
Save attakei/cb6c14ac471f6b8df4e6 to your computer and use it in GitHub Desktop.
Update AWS Lambda functions by AWS S3 and Lambda
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
# -*- coding:utf8 -*- | |
""" | |
""" | |
from __future__ import unicode_literals | |
import boto3 | |
from botocore.exceptions import ClientError | |
import zipfile | |
import json | |
__author__ = 'attakei' | |
class S3Object(object): | |
def __init__(self, region, bucket, key): | |
self.region = region | |
self.bucket = bucket | |
self.key = key | |
def lambda_handler(event, context): | |
"""Updates function from lambda | |
""" | |
records = event.get('Records', []) | |
for record in records: | |
if record['eventSource'] != 'aws:s3': | |
print('pass') | |
continue | |
s3_object = S3Object(record['awsRegion'], record['s3']['bucket']['name'], record['s3']['object']['key']) | |
_update_functions('sharequiz', 'test', s3_object) | |
def _update_functions(project, env, s3_object): | |
project_zip_path = '/tmp/project.zip' | |
s3 = boto3.resource('s3') | |
bucket = s3.Bucket(s3_object.bucket) | |
bucket.download_file(s3_object.key, project_zip_path) | |
with zipfile.ZipFile(project_zip_path) as zfp: | |
handlers_json = zfp.read('functions.json') | |
functions = json.loads(handlers_json) | |
_lambda = boto3.client('lambda') | |
for function in functions: | |
try: | |
_lambda.create_function( | |
Runtime='python2.7', | |
Code={'S3Bucket': s3_object.bucket, 'S3Key': s3_object.key,}, | |
**function) | |
except ClientError as err: | |
_lambda.update_function_configuration(**function) | |
_lambda.update_function_code( | |
FunctionName=function['FunctionName'], | |
S3Bucket=s3_object.bucket, | |
S3Key=s3_object.key, | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment