Delete S3 Bucket and Its objects from AWS / EC2 / Jump Server

Without leaving the AWS CLI, you can create or delete a bucket after you have the necessary permissions to read and write S3 buckets.

Using your EC2 instance, jump server, or AWS Cli, the following command helps delete an S3 bucket.

To check if you can access the S3, execute the below command.

aws s3 ls

It will return the list of the buckets from S3.

The following error indicates that you do not have the required rights on S3 buckets.
ls: cannot access s3-mysql-bucket: Transport endpoint is not connected.

If you are trying to copy or move files you’ll see the following error.
An error occurred (InvalidAccessKeyId) when calling the PutObject operation: The AWS Access Key Id you provided does not exist in our records.

Once you have access, execute the following to delete the buckets. You can only delete buckets that don’t have any objects in them. Make sure the bucket is empty.

aws s3api delete-bucket –bucket test-bucket –region us-east-2

If your bucket does not have versioning enabled, you can use the rb (remove bucket) AWS CLI command with the –force parameter to delete the bucket and all the objects in it. This command deletes all objects first and then deletes the bucket.

aws s3 rb s3://bucket-name –force

To delete all versioned objects in an S3 bucket with versioning enabled, you have to run the aws s3api delete-objects AWS CLI command with additional parameters:

aws s3api delete-objects –bucket bucket-name \
–delete “$(aws s3api list-object-versions \
–bucket “bucket-name” \
–output=json \
–query='{Objects: Versions[].{Key:Key,VersionId:VersionId}}’)”

The following command will delete all objects in an S3 bucket with versioning disabled.

aws s3 rm s3://mybucket –recursive

While creating a bucket, please remember to use a name that S3 can accept because S3 bucket names must be globally unique. If the name is already claimed by someone else, an error will be thrown.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s