Delete all versions of an object in S3 using python?

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

    This post was super helpful without this we would have spent tremendous amount of time cleaning up our S3 folders.

    We had a requirement to clean up specific folders only. So I tried the following code and it worked like a charm. Also note that I am iterating through the 10 times to delete more than 1000 objects limit that function has. Feel free to modify the limit as you wish.

    import boto3
    session = boto3.Session(aws_access_key_id='',aws_secret_access_key='')
    
    bucket_name = ''
    object_name = ''
    
    s3 = session.client('s3')
    
    for i in range(10):
       versions = s3.list_object_versions (Bucket = bucket_name, Prefix = object_name)
    #print (versions)
       version_list = versions.get('Versions')
       for version in version_list:
          keyName = version.get('Key')
          versionId = version.get('VersionId')
          print (keyName + ':' + versionId)
          s3.delete_object(Bucket = bucket_name, Key= keyName, VersionId = versionId)
       marker_list = versions.get('DeleteMarkers')
    #print(marker_list)
       for marker in marker_list:
          keyName1 = marker.get('Key')
          versionId1 = marker.get('VersionId')
          print (keyName1 + ':' + versionId1)
          s3.delete_object(Bucket = bucket_name, Key= keyName1, VersionId = versionId1)
    

提交回复
热议问题