Delete all versions of an object in S3 using python?

后端 未结 9 2010
既然无缘
既然无缘 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:42

    this script will delete all version of all object with prefix -

    s3 = boto3.resource("s3")
    client = boto3.client("s3")
    s3_bucket = s3.Bucket(bucket_name)
    for obj in s3_bucket.objects.filter(Prefix=""):
    
        response = client.list_object_versions(Bucket=bucket_name, Prefix=obj.key)
    
        while "Versions" in response:
            to_delete = [
                {"Key": ver["Key"], "VersionId": ver["VersionId"]}
                for ver in response["Versions"]
            ]
    
            delete = {"Objects": to_delete}
    
            client.delete_objects(Bucket=bucket_name, Delete=delete)
            response = client.list_object_versions(Bucket=bucket_name, Prefix=obj.key)
    
        client.delete_object(Bucket=bucket_name, Key=obj.key)
    

提交回复
热议问题