Delete all buckets whose name starts with the string parameter. Works on versioning buckets and buckets containing objects.
# Delete all buckets whose name starts with the string parameter. Works on versioning buckets and buckets containing objects.
# Usage:
# deleteBucket "bucketname" Deletes buckets whose name starts with 'bucketname'
deleteBucket()
{
BUCKETS=`aws s3api list-buckets --output text --query "Buckets[?starts_with(Name, '$1')].Name"`
IFS=$'\t'
for BUCKET in $BUCKETS; do :
echo starting to remove bucket $BUCKET
aws s3api delete-objects --bucket $BUCKET --delete \
"$(aws s3api list-object-versions --bucket $BUCKET --query='{Objects: Versions[].{Key:Key,VersionId:VersionId}}')"
aws s3api delete-objects --bucket $BUCKET --delete \
"$(aws s3api list-object-versions --bucket $BUCKET --query='{Objects: DeleteMarkers[].{Key:Key,VersionId:VersionId}}')"
aws s3 rb s3://$BUCKET --force
aws s3api list-buckets --query "Buckets[?starts_with(Name, '$BUCKET')].Name"
done
unset IFS
}
There might be enhancements around suppressing noise or deleting old buckets with spaces in their names, maybe.