1
votes

I have a S3 bucket with versioning enabled, configured to send notification events to Lambda. I need to process deleted objects from that bucket when the s3:ObjectRemoved:* event is received.

The event contains the versionId of the deleted object.

Is there a way to discover the versionId of the immediately previous version of the deleted object and fetch that version using the aws-sdk?

Or, alternatively, is there a way to get the deleted object using aws-sdk?

(I'm using the JavaScript aws-sdk)

1
Can't try this at the moment, but you should be able to call the S3 "list-object-versions" API to get all the object versions. I'd give a link but you didn't specify which programming language you are using. - Mark B
Thanks @mark-b, that works. I also edited the question to specify the language (JavaScript). Got it done with a multi-step process: 1. Get the list of versions with s3.listObjectVersions 2. Get the wanted version from the list 3. Get the specific object, passing VersionId as argument in s3.getObject({ Bucket: <bucket_name>, Key: <object_name>, VersionId: <version_from_step_2> }) - andreswebs

1 Answers

4
votes

It can be done with a 3-step process:

  1. Get the list of versions with listObjectVersions
  2. Get the wanted version from the list
  3. Get the specific object, passing VersionId as argument in getObject
const AWS = require('aws-sdk');
const s3 = new AWS.S3();

async function getDeletedObject (event, context) {

    let params = {
        Bucket: 'my-bucket',
        Prefix: 'my-file'
    };


    try {
        const previousVersion =  await s3.listObjectVersions(params)
            .promise()
            .then(result => {
                const versions = result.Versions;
                // get previous versionId
                return versions[0].VersionId;
             });

         params = {
              Bucket: 'my-bucket',
              Key: 'my-file',
              VersionId: previousVersion
         };

         const deletedObject = await s3.getObject(params)
             .promise()
             .then(response => response.Body.toString('utf8'));

         return deletedObject;
    }

    catch (error) {
        console.log(error);
        return;
    }

}