Search code examples
amazon-s3keyversioningbotoundelete

Can I undelete/access legacy S3 key that was created before bucket switched to versioning?


I have an S3 bucket that has a bunch of legacy files. I just switched on versioning and am trying to figure out what sort of deletion protection this gives me for the legacy files, compared to new files uploaded since after the switch. Here's some sample code:

import boto
c = boto.connect_s3()
bucket = c.get_bucket('my-bucket')
pfx='myfolder/subfolder/'
i = 0
for k in bucket.list_versions(prefix=pfx):
    if type(k) == boto.s3.deletemarker.DeleteMarker:
        print "DM %s %s" % (k.name, k.version_id)
    else:
        s = k.get_contents_as_string()
        print "REG %s %s %d" % (k.name, k.version_id, len(s))

the pfx contains some legacy files, so the first time I ran this I got something like this:

REG myfolder/subfolder/ null 0
REG myfolder/subfolder/f1 null 369
REG myfolder/subfolder/f2 null 427
REG myfolder/subfolder/f3 null 141

I then deleted f2 using the S3Browser tool. When I reran the code above, i got this:

REG myfolder/subfolder/ null 0
REG myfolder/subfolder/f1 null 369
DM myfolder/subfolder/f2 KPNaxqBeIrCGKUx3tYUsRDwWzKbX06
REG myfolder/subfolder/f2 null 427
REG myfolder/subfolder/f3 null 141

Question is: is there a way of retrieving/undeleting the (only) version of f2 I just deleted?


Solution

  • Once you enable versioning on a bucket it is enabled for all objects in the bucket. Any object that is deleted, regardless of whether it was created before or after versioning was enabled, will result in a DeleteMarker being written to the bucket. The object, and any previous versions of the object, will still be there unless you explicitly do a versioned delete operation.

    So, if you call list_versions(prefix='myfolder/subfolder/f2') on that bucket it should return a Key object for the version which remains. You should be able to use the normal methods of the Key object to retrieve the contents of the object.