Skip to content

Commit 61c2e31

Browse files
author
Scott Collins
committed
Added abort_multipart_uploads.py utility script
1 parent 20bc725 commit 61c2e31

1 file changed

Lines changed: 74 additions & 0 deletions

File tree

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
"""
2+
abort_multipart_uploads.py
3+
4+
Utility script to abort unclosed multipart uploads in an S3 bucket.
5+
Partially generated by GitHub Copilot.
6+
"""
7+
import json
8+
import subprocess
9+
import sys
10+
11+
12+
def list_multipart_uploads(bucket):
13+
"""
14+
List unclosed multipart uploads in an S3 bucket.
15+
16+
Parameters
17+
----------
18+
bucket : str
19+
Name of the S3 bucket.
20+
21+
Returns
22+
-------
23+
upload_list : list
24+
List of dictionaries containing information about unclosed multipart uploads.
25+
26+
"""
27+
cmd = ["aws", "s3api", "list-multipart-uploads", "--bucket", bucket, "--output", "json"]
28+
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
29+
upload_ids = json.loads(result.stdout)
30+
print("Found %d unclosed multipart uploads in bucket '%s'." % (len(upload_ids.get("Uploads", [])), bucket))
31+
return upload_ids["Uploads"]
32+
33+
34+
def abort_multipart_upload(bucket, key, upload_id):
35+
"""
36+
Abort a specific multipart upload in an S3 bucket.
37+
38+
Parameters
39+
----------
40+
bucket : str
41+
Name of the S3 bucket.
42+
key : str
43+
S3 key for the object being multipart uploaded.
44+
upload_id : dict
45+
Dictionary containing the upload ID and other metadata.
46+
47+
"""
48+
cmd = ["aws", "s3api", "abort-multipart-upload", "--bucket", bucket, "--key", key, "--upload-id", upload_id]
49+
subprocess.run(cmd, check=True)
50+
print(f"Aborted multipart upload: {key=} {upload_id=}")
51+
52+
53+
def main():
54+
"""Main function to abort multipart uploads in an S3 bucket."""
55+
if len(sys.argv) != 2:
56+
print("Usage: python abort_multipart_uploads.py <bucket>")
57+
sys.exit(1)
58+
59+
bucket = sys.argv[1]
60+
61+
try:
62+
upload_ids = list_multipart_uploads(bucket)
63+
if not upload_ids:
64+
print("No multipart uploads found for the specified bucket.")
65+
return
66+
for upload_id in upload_ids:
67+
abort_multipart_upload(bucket, upload_id["Key"], upload_id["UploadId"])
68+
except subprocess.CalledProcessError as e:
69+
print("Error:", e.stderr)
70+
sys.exit(1)
71+
72+
73+
if __name__ == "__main__":
74+
main()

0 commit comments

Comments
 (0)