Skip to content

Instantly share code, notes, and snippets.

@uurtech
Created May 21, 2023 18:08
Show Gist options
  • Save uurtech/054ae1b50532a13c6b4d5ddea94ef95d to your computer and use it in GitHub Desktop.
Save uurtech/054ae1b50532a13c6b4d5ddea94ef95d to your computer and use it in GitHub Desktop.
Delete Older Versions of Bucket files
import boto3
import json
# Configure the AWS SDK with your credentials
session = boto3.Session(
aws_access_key_id='ACCESS_KEY',
aws_secret_access_key='ACESS_SECRET_ACCESS_KEY',
region_name='eu-west-1' # Replace with your desired region
)
# Create an S3 service client
s3 = session.client('s3')
# Specify the bucket name
bucket_name = 'bucket_name'
# Call the S3 API to list object versions
# this will get all buckets recursively
response = s3.list_object_versions(Bucket=bucket_name)
# Retrieve the versions array from the response
versions = response['Versions']
# Process each version
for version in versions:
# Skip the latest version (null version ID)
if 'VersionId' in version and version['IsLatest'] is False:
s3.delete_object(
Bucket=bucket_name,
Key=version['Key'],
VersionId=version['VersionId']
)
print(f"Deleted version: {version['VersionId']} of object: {version['Key']}")
@uurtech
Copy link
Author

uurtech commented May 22, 2023

if you put version id on cli, you have have it bash version of this script, its scary to run delete command on cli but make sure you have version id on your command

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment