Skip to content
Snippets Groups Projects

Lambda extract files from zip on s3 and send email on error.

  • Clone with SSH
  • Clone with HTTPS
  • Embed
  • Share
    The snippet can be accessed without any authentication.
    Authored by David Sinclair
    Edited
    file.py 1.90 KiB
    import json
    import boto3
    import zipfile
    import os
    from io import BytesIO
    
    def lambda_handler(event, context):
        # TODO implement
        s3_resource = boto3.resource('s3')
        bucket = os.environ['BUCKET']
        aws_access_key = os.environ['AWS_ACCESS_KEY_ID_2']
        aws_secret_key = os.environ['AWS_SECRET_ACCESS_KEY_2']
        source_key = event['Records'][0]['s3']['object']['key']
        recipient_email = os.environ['RECIPIENT_EMAIL']
        sender_email = os.environ['SENDER_EMAIL']
        folder_processed = "processed/"
        try:
            zip_obj = s3_resource.Object(bucket_name=bucket, key=source_key)
            buffer = BytesIO(zip_obj.get()["Body"].read())
    
            z = zipfile.ZipFile(buffer)
            for filename in z.namelist():
                file_info = z.getinfo(filename)
                file_name = os.path.basename(filename)
                if filename.lower().endswith(('.jpg', '.jpeg')):
                    s3_resource.meta.client.upload_fileobj(
                        z.open(filename),
                        Bucket=bucket,
                        Key=f'{folder_processed}{file_name}'
            )
             return {
            'statusCode': 200,
            'body': json.dumps('Successfully Extracted the Files and Processed them.')
            }
        except Exception as e:
            print(f"Error processing file {source_key}: {e}")
            
            # Send error email
            ses.send_email(
                Source=sender_email,
                Destination={'ToAddresses': [recipient_email]},
                Message={
                    'Subject': {'Data': 'Lambda Function Error Extract_CertiLock_Upload_Production'},
                    'Body': {
                        'Text': {
                            'Data': f"Error processing file {source_key}: {str(e)}"
                        }
                    }
                }
            )
            return {
                'statusCode': 500,
                'body': f"Error processing file {source_key}."
            }
       
    0% Loading or .
    You are about to add 0 people to the discussion. Proceed with caution.
    Please register or to comment