A quick and merry lab on S3 and Lambda – nice and easy

Services Covered

  • S3 S3
  • lambda 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



AWS account

Lab steps

  1. Create a S3 :snowman: bucket.

  2. 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
           Body=compress(body, key),
       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)
       return data.read()
  3. :santa:Add trigger and select S3.
  4. :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:

Lab files