Delete all versions of an object in S3 using python?

后端 未结 9 2013
既然无缘
既然无缘 2021-02-05 17:28

I have a versioned bucket and would like to delete the object (and all of its versions) from the bucket. However, when I try to delete the object from the console, S3 simply add

相关标签:
9条回答
  • 2021-02-05 18:04

    I had trouble using the other solutions to this question so here's mine.

    import boto3
    bucket = "bucket name goes here"
    filename = "filename goes here"
    
    client = boto3.client('s3')
    paginator = client.get_paginator('list_object_versions')
    response_iterator = paginator.paginate(Bucket=bucket)
    for response in response_iterator:
        versions = response.get('Versions', [])
        versions.extend(response.get('DeleteMarkers', []))
        for version_id in [x['VersionId'] for x in versions
                           if x['Key'] == filename and x['VersionId'] != 'null']:
            print('Deleting {} version {}'.format(filename, version_id))
            client.delete_object(Bucket=bucket, Key=filename, VersionId=version_id)
    

    This code deals with the cases where

    • object versioning isn't actually turned on
    • there are DeleteMarkers
    • there are no DeleteMarkers
    • there are more versions of a given file than fit in a single API response

    Mahesh Mogal's answer doesn't delete DeleteMarkers. Mangohero1's answer fails if the object is missing a DeleteMarker. Hari's answer repeats 10 times (to workaround missing pagination logic).

    0 讨论(0)
  • 2021-02-05 18:04

    Fewer line solution.

    import boto3
    
    def delete_versions(bucket, objects=None): # `objects` is either list of str or None
      bucket = boto3.resource('s3').Bucket(bucket)
      if objects: # delete specified objects
        [version.delete() for version in bucket.object_versions.all() if version.object_key in objects]
      else: # or delete all objects in `bucket`
        [version.delete() for version in bucket.object_versions.all()]
    
    0 讨论(0)
  • 2021-02-05 18:05

    The documentation is helpful here:

    1. When versioning is enabled in an S3 bucket, a simple DeleteObject request cannot permanently delete an object from that bucket. Instead, Amazon S3 inserts a delete marker (which is effectively a new version of the object with its own version ID).
    2. When you try to GET an object whose current version is a delete marker, S3 behaves as if the object has been deleted (even though it has not) and returns a 404 error.
    3. To permanently delete an object from a versioned bucket, use DeleteObject, with the relevant version ID, for each and every version of the object (and that includes the delete markers).
    0 讨论(0)
提交回复
热议问题