To list S3 buckets using AWS CLI and delete buckets based on a specific pattern, you can follow the steps below. Here, we explain how to delete buckets whose names start with wby.
Prerequisites
- AWS CLI is installed.
- Appropriate AWS credentials and access permissions are configured.
Step 1: List Buckets
First, use the installed AWS CLI to list all S3 buckets:
Step 2: Delete Matching Buckets
To delete buckets starting with wby, use a shell script to filter matching buckets and delete them.
The following script searches for bucket names starting with wby and deletes each bucket. Warning: This script will delete buckets and all objects within them. Please verify your data backups before running.
This script does the following:
aws s3 lsretrieves the bucket list.awk '{print $3}'extracts only the bucket names.grep '^wby'filters bucket names starting withwby.while read bucketloop deletes each bucket.
Notes
- Ensure that necessary data is backed up before deleting buckets.
- If a bucket is not empty, the
aws s3 rb --forceoption is used to delete the bucket along with all objects inside it. - Before running the actual deletion commands, it is recommended to insert an
echostatement to verify which buckets will be deleted.