0

I'm trying to delete an object on my S3 bucket with the aws-sdk for Node.js using this s3.deleteObject api:

async function deleteObjectAsync(bucket, key) {
    try {
        var extras = {
            Bucket: bucket,
            Key: key
        };
        const data = await s3
            .deleteObject(extras)
            .promise();
        return data;
    } catch (err) {
        console.log(err);
    }
}//deleteObjectAsync

used like

(async (bucket, keys) => {
    for (const key of keys) {
        const result = await deleteObjectAsync(bucket, key);
        console.log(result);
    }
})(my_bucket, keys);

I get - as result - a DeleteMarker field and a VersionId:

{ DeleteMarker: true, VersionId: '2wMteXstTAn6e.rsTS6wHVSerXuUMNLXw' }

but the object does not seem to be deleted on the S3 bucket, but marked for deletion.

When using the Python api:

def delete_key(bucket, key):
    deleted = True
    try:
        s3 = boto3.client('s3')
        res = s3.delete_object(Bucket=bucket, Key=key)
    except Exception as e:
        print("deleted key:%s error:%s" % (key,e) )
        deleted = False
        pass
    return deleted

the file is immediately deleted. Why?

3
  • 1
    The behavior you see is exactly the one explained on its documentation page. I don't understand why it works differently in Python; it should behave the same since they use the same API endpoint. Commented May 6, 2021 at 18:50
  • @guzmonne good point. In fact I wrote a delete object for versioned bucket, but it does not work as expected - gist.github.com/loretoparisi/0058675d13d1115e7b46b1b66433b327 Commented May 6, 2021 at 18:58
  • If you use the deleteObjects method instead, does the behavior changes? Commented May 6, 2021 at 19:07

1 Answer 1

2

To successfully delete and object from a versioned bucket is super simple, but the documentation isn't very clear on how one should do it.

From your own example above, here follows how you could do it:

async function deleteObjectAsync(bucket, key) {
  try {
    const params = {
      Bucket: bucket,
      Key: key,
      VersionId: 'null'
    };

    return await s3.deleteObject(params).promise();
  } catch (err) {
    console.error(err);
  }
}

The trick is to pass the 'null' string as VersionId when the object doesn't have a VersionId yet. When it does then you have to delete all the previous versions and then delete the 'null' version , which is the "original one".

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, it works. For the sake of glory, and to avoid further headaches to other devs, I have put all possibilities here: gist.github.com/loretoparisi/3994ff64d1181572d6ae1855862e0816

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.