Delete Multiple Objects of a Bucket
Components
- Credentials
- Bucket Name
- Objects' List
- .NET
- PHP
- Python
- Javascript
- GO
using Amazon;
using Amazon.S3;
using Amazon.S3.Model;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace DeleteObjects
{
class DeleteObjects
{
private const string bucketName = "<BUCKET_NAME>";
private static IAmazonS3 _s3Client;
public static void Main()
{
var awsCredentials = new Amazon.Runtime.BasicAWSCredentials("<ACCESS-KEY>", "<SECRET-KEY>");
var config = new AmazonS3Config { ServiceURL = "<ENDPOINT>" };
_s3Client = new AmazonS3Client(awsCredentials, config);
DeleteObjectsAsync().Wait();
}
private static async Task DeleteObjectsAsync()
{
DeleteObjectsRequest request = new DeleteObjectsRequest
{
BucketName = bucketName,
Objects = new List<KeyVersion>
{
new KeyVersion() {Key = "Item1"},
// Versioned item
new KeyVersion() { Key = "Item2", VersionId = "Rej8CiBxcZKVK81cLr39j27Y5FVXghDK", },
// Item in subdirectory
new KeyVersion() { Key = "Logs/error.txt"}
}
};
try
{
await _s3Client.DeleteObjectsAsync(request);
Console.WriteLine($"Objects successfully deleted from {bucketName} bucket");
}
catch (AmazonS3Exception amazonS3Exception)
{
Console.WriteLine("An AmazonS3Exception was thrown. Exception: " + amazonS3Exception.ToString());
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.ToString());
}
}
}
}
<?php
require('client.php');
$bucket = '<BUCKET_NAME>';
try {
$result = $client->deleteObjects([
'Bucket' => $bucket, // REQUIRED
'BypassGovernanceRetention' => true || false,
'Delete' => [ // REQUIRED
'Objects' => [ // REQUIRED
[
'Key' => '<string>', // REQUIRED
'VersionId' => '<string>',
],
// ...
],
'Quiet' => true || false,
],
'ExpectedBucketOwner' => '<string>',
'MFA' => '<string>',
'RequestPayer' => 'requester',
]);
var_dump($result);
} catch (AwsException $e) {
// Display error message
echo $e->getMessage();
echo "\n";
}
import boto3
import logging
from botocore.exceptions import ClientError
logging.basicConfig(level=logging.INFO)
try:
s3_resource = boto3.resource(
's3',
endpoint_url='<ENDPOINT>',
aws_access_key_id='<ACCESS-KEY>',
aws_secret_access_key='<SECRET-KEY>'
)
except Exception as exc:
logging.error(exc)
else:
try:
bucket = s3_resource.Bucket('<BUCKET_NAME>')
response = bucket.delete_objects(
Delete={
'Objects': [
{
'Key': 'string',
'VersionId': 'string'
},
],
'Quiet': True|False
},
MFA='string',
RequestPayer='requester',
BypassGovernanceRetention=True|False,
ExpectedBucketOwner='string'
)
logging.info(response)
except ClientError as exc:
logging.error(exc)
// Import required AWS SDK clients and commands for Node.js
const { S3Client, DeleteBucketCorsCommand } = 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 BUCKET_NAME = "<BUCKET_NAME>";
const run = async () => {
try {
const response = await s3.send(
new DeleteObjectsCommand({
Bucket: BUCKET_NAME,
Delete: {
Objects: [
{
Key: "key1",
},
{
Key: "key2",
},
],
},
})
);
console.log("Success", response);
} catch (err) {
console.log("Error", err);
}
};
run();
package main
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"fmt"
"os"
)
// Deletes objects from bucket
//
// Usage:
// go run s3_delete_objects.go BUCKET
func main() {
if len(os.Args) < 2 {
exitErrorf("Bucket name: go run", os.Args[0], "BUCKET")
}
bucket := os.Args[1]
// Initialize a session in us-west-2 that the SDK will use to load
// credentials from the shared credentials file ~/.aws/credentials.
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>"),
})
params := &s3.DeleteObjectsInput{
Bucket: &bucket,
Delete: &s3.Delete{
Objects: []*s3.ObjectIdentifier{
{
Key: aws.String("HappyFace.jpg"),
VersionId: aws.String("2LWg7lQLnY41.maGB5Z6SWW.dcq0vx7b"),
},
{
Key: aws.String("HappyFace.jpg"),
VersionId: aws.String("yoz3HB.ZhCS_tKVEmIOr7qYyyAaZSKVd"),
},
},
Quiet: aws.Bool(false),
},
}
// Delete objects
_, err = svc.DeleteObjects(params)
if err != nil {
exitErrorf(err.Error())
}
fmt.Println("Congratulations. You deleted objects from bucket", 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_website.go:
go run s3_delete_objects.go BUCKET_NAME