A quick and merry lab on S3 and Lambda – nice and easy
Services Covered
S3
Lambda
Lab description
Upload a Christmas tree into S3 bucket and let Lambda do it’s .
Learning Objectives
- Create amazing Lambda
- Send Christmas tree
- Let Events call the Lambda and do the magic
Lab date
24-12-2021
Prerequisites
AWS account
Lab steps
- Create a S3 :snowman: bucket.
- Create a Lambda function with Python as runtime.
import os, zipfile from io import BytesIO import boto3 s3 = boto3.client('s3') def lambda_handler(event, context): # read bucket and key from event data record = event['Records'][0]['s3'] bucket = record['bucket']['name'] key = record['object']['key'] # generate new key name new_key = "zip/%s.zip" % os.path.basename(key) # read the source obj content body = s3.get_object(Bucket=bucket, Key=key)['Body'].read() # create new obj with compressed data s3.put_object( Body=compress(body, key), Key=new_key, Bucket=bucket, ) return "OK" def compress(body, key): data = BytesIO() with zipfile.ZipFile(data, 'w', zipfile.ZIP_DEFLATED) as f: f.writestr(os.path.basename(key), body) data.seek(0) return data.read()
- :santa:Add trigger and select S3.
- :santa:In your S3 bucket create a folder called images.Then upload a file to that folder.
This will invoke a Lambda function and create a new folder called zip with output file: