Skip to content

Instantly share code, notes, and snippets.

@alanmur
Created November 30, 2021 23:28
Show Gist options
  • Save alanmur/d105d3c2f7f3ee95bb4d1bd9a1fa3a12 to your computer and use it in GitHub Desktop.
Save alanmur/d105d3c2f7f3ee95bb4d1bd9a1fa3a12 to your computer and use it in GitHub Desktop.
CLI/sh: Delete AWS Buckets starting with the specified string (including versioned and non-empty)

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.

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