Let's imagine you have a S3 bucket that is versioned. It contains thousands of files. If you try to delete it you're warned because of the versions. You cannot select all files in AWS Console so a way to do this is from your command line:
aws s3 rm s3://YOUR_BUCKET --recursive
But what about the versions and maybe delete markers. We can use the following Python script:
#!/usr/bin/env python3
import boto3
bucket = 'YOUR_BUCKET'
s3_client = boto3.client('s3')
def remove_s3_object_versions(bucket):
response = s3_client.list_object_versions(Bucket=bucket)
versions = response.get('Versions', [])
for version in versions:
s3_client.delete_object(Bucket=bucket, Key=version['Key'], VersionId=version['VersionId'])
delete_markers = response.get('DeleteMarkers', [])
for marker in delete_markers:
s3_client.delete_object(Bucket=bucket, Key=marker['Key'], VersionId=marker['VersionId'])
remove_s3_object_versions(bucket)