Delete all versions of an object in S3 using python?

后端 未结 9 2012
既然无缘
既然无缘 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 17:44

    As a supplement to @jarmod's answer, here is a way I developed a workaround to "hard deleting" an object (with delete markered objects included);

    def get_all_versions(bucket, filename):
        s3 = boto3.client('s3')
        keys = ["Versions", "DeleteMarkers"]
        results = []
        for k in keys:
            response = s3.list_object_versions(Bucket=bucket)[k]
            to_delete = [r["VersionId"] for r in response if r["Key"] == filename]
        results.extend(to_delete)
        return results
    
    bucket = "YOUR BUCKET NAME"
    file = "YOUR FILE"
    
    for version in get_all_versions(bucket, file):
        s3.delete_object(Bucket=bucket, Key=file, VersionId=version)
    

提交回复
热议问题