Delete Bucket
Before deleting a bucket you must first delete all its objects.
Components
- Credentials
- Bucket Name
- .NET
- PHP
- Python
- Javascript
- GO
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX - License - Identifier: Apache - 2.0
using Amazon;
using Amazon.S3;
using System;
using System.Threading.Tasks;
namespace DeleteBucket
{
class DeleteBucket
{
// This example shows how to delete an existing empty bucket.
// The examples uses AWS SDK for .NET 3.5 and .NET 5.0.
private static IAmazonS3 _s3Client;
// Specify the name of the bucket to delete.
private const string BUCKET_NAME = "<BUCKET_NAME>";
static async Task Main()
{
var awsCredentials = new Amazon.Runtime.BasicAWSCredentials("<ACCESS-KEY>", "<SECRET-KEY>");
var config = new AmazonS3Config { ServiceURL = "<ENDPOINT>" };
_s3Client = new AmazonS3Client(awsCredentials, config);
// Now delete the bucket. If the bucket you are trying to
// delete contains any objects, the call will raise an exception.
Console.WriteLine($"\nDeleting bucket {BUCKET_NAME}...");
await DeletingBucketAsync(_s3Client, BUCKET_NAME);
}
/// <summary>
/// DeletingBucketAsync calls the DeleteBucketAsync method
/// to delete the S3 bucket bucketName.
/// </summary>
/// <param name="client">The Amazon S3 client object.</param>
/// <param name="bucketName">The name of the bucket to be deleted.</param>
static async Task DeletingBucketAsync(IAmazonS3 client, string bucketName)
{
try
{
var deleteResponse = await client.DeleteBucketAsync(bucketName);
Console.WriteLine($"\nResult: {deleteResponse.HttpStatusCode.ToString()}");
Console.WriteLine("Bucket successfully deleted");
}
catch(AmazonS3Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
}
<?php
require('client.php');
function deleteBucket($s3Client, $bucketName)
{
try {
$result = $s3Client->deleteBucket([
'Bucket' => $BUCKET_NAME,
]);
} catch (AwsException $e) {
return 'Error: ' . $e->getAwsErrorMessage();
}
}
echo deleteBucket($client, 'sample-bucket-4');
import boto3
import logging
from botocore.exceptions import ClientError
logging.basicConfig(level=logging.INFO)
try:
s3_resource = boto3.resource(
's3',
endpoint_url='endpoint_url',
aws_access_key_id='access_key',
aws_secret_access_key='secret_key'
)
except Exception as exc:
logging.error(exc)
else:
try:
bucket_name = 'sample-bucket_name'
bucket = s3_resource.Bucket(bucket_name)
bucket.delete()
except ClientError as exc:
logging.error(exc)
const { S3Client, DeleteBucketCommand } = require('@aws-sdk/client-s3');
// Create an S3 client service object
const s3 = new S3Client({
region: 'default',
endpoint: 'endpoint_url',
credentials: {
accessKeyId: 'access_key',
secretAccessKey: 'secret_key',
},
});
const run = async () => {
try {
const data = await s3.send(
new DeleteBucketCommand({
Bucket: 'sample-bucket'
})
);
console.log('Success', data);
} catch (err) {
console.log('Error', err);
}
}
run();
package main
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"fmt"
"os"
)
// Deletes an S3 Bucket in the region configured in the shared config
// or AWS_REGION environment variable.
//
// Usage:
// go run s3_delete_bucket BUCKET_NAME
func main() {
if len(os.Args) != 2 {
exitErrorf("bucket name required\nUsage: %s bucket_name", os.Args[0])
}
bucket := os.Args[1]
sess, err := session.NewSession(&aws.Config{
Credentials: credentials.NewStaticCredentials("<ACCESS_KEY>", "<SECRET_KEY>", ""),
})
svc := s3.New(sess, &aws.Config{
Region: aws.String("default"),
Endpoint: aws.String("<ENDPOINT_URL>"),
})
// Delete the S3 Bucket
// It must be empty or else the call fails
_, err = svc.DeleteBucket(&s3.DeleteBucketInput{
Bucket: aws.String(bucket),
})
if err != nil {
exitErrorf("Unable to delete bucket %q, %v", bucket, err)
}
// Wait until bucket is deleted before finishing
fmt.Printf("Waiting for bucket %q to be deleted...\n", bucket)
err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{
Bucket: aws.String(bucket),
})
if err != nil {
exitErrorf("Error occurred while waiting for bucket to be deleted, %v", bucket)
}
fmt.Printf("Bucket %q successfully deleted\n", bucket)
}
func exitErrorf(msg string, args ...interface{}) {
fmt.Fprintf(os.Stderr, msg+"\n", args...)
os.Exit(1)
}
The following command can be used to execute the aforementioned code, presuming the code file is called s3_delete_bucket.go:
go run s3_delete_bucket.go BUCKET_NAME