Thursday, August 3, 2023

Script to Empty and Delete AWS S3 Bucket in One Go

 This script deletes all the objects and version and then S3 bucket itself. Just login to your Linux terminal, make sure you have aws cli configured, and run the following shell script. Also make sure to do chmod +x <script name> to make your script executable.




#!/bin/bash


buckettodelete=$1


if [ -z "$buckettodelete" ] ; then

echo "Usage: $0 <buckettodelete>"

exit 1

fi


# Step 1: Delete objects

aws s3api delete-objects --bucket ${buckettodelete} --delete "$(aws s3api list-object-versions --bucket ${buckettodelete} --query='{Objects: Versions[].{Key:Key,VersionId:VersionId}}')" --output text


# Step 2: Delete markers

aws s3api delete-objects --bucket ${buckettodelete} --delete "$(aws s3api list-object-versions --bucket ${buckettodelete} --query='{Objects: DeleteMarkers[].{Key:Key,VersionId:VersionId}}')" --output text


# Step 3: Delete Bucket

aws s3 rb s3://${buckettodelete}/ --force

No comments: