AWS Lambda Sample Code to Delete Specific Files Uploaded to S3

Tadashi Shigeoka ·  Tue, August 17, 2021

I’ll introduce sample code for AWS Lambda to delete specific files uploaded to S3.

AWS

Background: Want to detect and delete files that shouldn't be uploaded to S3

The topic of this article is to detect and delete files that would be problematic if uploaded to S3, as a countermeasure for when unexpected files are uploaded to S3 by some means.

Sample Code for Lambda Function to Delete Files with ContentType: text/html Uploaded to S3

I created the base using the article チュートリアル: Amazon S3 トリガーを使用して Lambda 関数を呼び出す - AWS Lambda as reference.

The following Lambda function is the sample code, so please make use of it.

const aws = require('aws-sdk');
const s3 = new aws.S3({ apiVersion: '2006-03-01' });

exports.handler = async (event, context) => {
  const bucket = event.Records[0].s3.bucket.name;
  const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\\+/g, ' '));
  const params = {
    Bucket: bucket,
    Key: key,
  };
  try {
    const { ContentType } = await s3.getObject(params).promise();
    console.log('CONTENT TYPE:', ContentType);
    if (ContentType === 'text/html') {
      await s3.deleteObject(params).promise();
      console.log('s3.deleteObject:', params);
      return;
    }
    return;
  } catch (err) {
    throw new Error(err);
  }
};

That’s all from the Gemba on wanting to delete specific files uploaded to S3 using a Lambda function.