Utilizzare DeleteBucket con un AWS SDKo CLI - Amazon Simple Storage Service

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

Utilizzare DeleteBucket con un AWS SDKo CLI

I seguenti esempi di codice mostrano come utilizzareDeleteBucket.

Gli esempi di operazioni sono estratti di codice da programmi più grandi e devono essere eseguiti nel contesto. È possibile visualizzare questa operazione nel contesto nel seguente esempio di codice:

.NET
AWS SDK for .NET
Nota

C'è di più su. GitHub Trova l'esempio completo e scopri come configurare ed eseguire in AWS Repository di esempi di codice.

/// <summary> /// Shows how to delete an Amazon S3 bucket. /// </summary> /// <param name="client">An initialized Amazon S3 client object.</param> /// <param name="bucketName">The name of the Amazon S3 bucket to delete.</param> /// <returns>A boolean value that represents the success or failure of /// the delete operation.</returns> public static async Task<bool> DeleteBucketAsync(IAmazonS3 client, string bucketName) { var request = new DeleteBucketRequest { BucketName = bucketName, }; var response = await client.DeleteBucketAsync(request); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; }
  • Per API i dettagli, vedere DeleteBucketin AWS SDK for .NET APIRiferimento.

Bash
AWS CLI con script Bash
Nota

C'è altro da fare. GitHub Trova l'esempio completo e scopri come configurare ed eseguire in AWS Repository di esempi di codice.

############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################### # function delete_bucket # # This function deletes the specified bucket. # # Parameters: # $1 - The name of the bucket. # Returns: # 0 - If successful. # 1 - If it fails. ############################################################################### function delete_bucket() { local bucket_name=$1 local response response=$(aws s3api delete-bucket \ --bucket "$bucket_name") # shellcheck disable=SC2181 if [[ $? -ne 0 ]]; then errecho "ERROR: AWS reports s3api delete-bucket failed.\n$response" return 1 fi }
  • Per API i dettagli, vedere DeleteBucketin AWS CLI Riferimento ai comandi.

C++
SDKper C++
Nota

C'è altro su. GitHub Trova l'esempio completo e scopri come configurare ed eseguire in AWS Repository di esempi di codice.

bool AwsDoc::S3::deleteBucket(const Aws::String &bucketName, const Aws::S3::S3ClientConfiguration &clientConfig) { Aws::S3::S3Client client(clientConfig); Aws::S3::Model::DeleteBucketRequest request; request.SetBucket(bucketName); Aws::S3::Model::DeleteBucketOutcome outcome = client.DeleteBucket(request); if (!outcome.IsSuccess()) { const Aws::S3::S3Error &err = outcome.GetError(); std::cerr << "Error: deleteBucket: " << err.GetExceptionName() << ": " << err.GetMessage() << std::endl; } else { std::cout << "The bucket was deleted" << std::endl; } return outcome.IsSuccess(); }
  • Per API i dettagli, vedere DeleteBucketin AWS SDK for C++ APIRiferimento.

CLI
AWS CLI

Il comando seguente elimina un bucket denominato: my-bucket

aws s3api delete-bucket --bucket my-bucket --region us-east-1
  • Per i API dettagli, vedere in DeleteBucketAWS CLI Riferimento ai comandi.

Go
SDKper Go V2
Nota

C'è altro da fare. GitHub Trova l'esempio completo e scopri come configurare ed eseguire in AWS Repository di esempi di codice.

// BucketBasics encapsulates the Amazon Simple Storage Service (Amazon S3) actions // used in the examples. // It contains S3Client, an Amazon S3 service client that is used to perform bucket // and object actions. type BucketBasics struct { S3Client *s3.Client } // DeleteBucket deletes a bucket. The bucket must be empty or an error is returned. func (basics BucketBasics) DeleteBucket(bucketName string) error { _, err := basics.S3Client.DeleteBucket(context.TODO(), &s3.DeleteBucketInput{ Bucket: aws.String(bucketName)}) if err != nil { log.Printf("Couldn't delete bucket %v. Here's why: %v\n", bucketName, err) } return err }
  • Per API i dettagli, vedere DeleteBucketin AWS SDK for Go APIRiferimento.

Java
SDKper Java 2.x
Nota

C'è di più su. GitHub Trova l'esempio completo e scopri come configurare ed eseguire in AWS Repository di esempi di codice.

/** * Deletes an S3 bucket asynchronously. * * @param bucket the name of the bucket to be deleted * @return a {@link CompletableFuture} that completes when the bucket deletion is successful, or throws a {@link RuntimeException} * if an error occurs during the deletion process */ public CompletableFuture<Void> deleteBucketAsync(String bucket) { DeleteBucketRequest deleteBucketRequest = DeleteBucketRequest.builder() .bucket(bucket) .build(); CompletableFuture<DeleteBucketResponse> response = getAsyncClient().deleteBucket(deleteBucketRequest); response.whenComplete((deleteRes, ex) -> { if (deleteRes != null) { logger.info(bucket + " was deleted."); } else { throw new RuntimeException("An S3 exception occurred during bucket deletion", ex); } }); return response.thenApply(r -> null); }
  • Per API i dettagli, vedere DeleteBucketin AWS SDK for Java 2.x APIRiferimento.

JavaScript
SDKper JavaScript (v3)
Nota

C'è di più su. GitHub Trova l'esempio completo e scopri come configurare ed eseguire in AWS Repository di esempi di codice.

Elimina il bucket.

import { DeleteBucketCommand, S3Client } from "@aws-sdk/client-s3"; const client = new S3Client({}); // Delete a bucket. export const main = async () => { const command = new DeleteBucketCommand({ Bucket: "test-bucket", }); try { const response = await client.send(command); console.log(response); } catch (err) { console.error(err); } };
PHP
SDK per PHP
Nota

C'è altro da fare GitHub. Trova l'esempio completo e scopri come configurare ed eseguire in AWS Repository di esempi di codice.

Elimina un bucket vuoto.

$s3client = new Aws\S3\S3Client(['region' => 'us-west-2']); try { $this->s3client->deleteBucket([ 'Bucket' => $this->bucketName, ]); echo "Deleted bucket $this->bucketName.\n"; } catch (Exception $exception) { echo "Failed to delete $this->bucketName with error: " . $exception->getMessage(); exit("Please fix error with bucket deletion before continuing."); }
  • Per API i dettagli, vedere DeleteBucketin AWS SDK for PHP APIRiferimento.

PowerShell
Strumenti per PowerShell

Esempio 1: questo comando rimuove tutti gli oggetti e le versioni degli oggetti dal bucket 'test-files', quindi elimina il bucket. Il comando richiederà una conferma prima di procedere. Aggiungere l'interruttore -Force per sopprimere la conferma. Nota che i bucket che non sono vuoti non possono essere eliminati.

Remove-S3Bucket -BucketName test-files -DeleteBucketContent
  • Per API i dettagli, vedere DeleteBucketin AWS Tools for PowerShell Riferimento al cmdlet.

Python
SDKper Python (Boto3)
Nota

C'è di più su. GitHub Trova l'esempio completo e scopri come configurare ed eseguire in AWS Repository di esempi di codice.

class BucketWrapper: """Encapsulates S3 bucket actions.""" def __init__(self, bucket): """ :param bucket: A Boto3 Bucket resource. This is a high-level resource in Boto3 that wraps bucket actions in a class-like structure. """ self.bucket = bucket self.name = bucket.name def delete(self): """ Delete the bucket. The bucket must be empty or an error is raised. """ try: self.bucket.delete() self.bucket.wait_until_not_exists() logger.info("Bucket %s successfully deleted.", self.bucket.name) except ClientError: logger.exception("Couldn't delete bucket %s.", self.bucket.name) raise
  • Per API i dettagli, vedere DeleteBucketin AWS SDKper Python (Boto3) Reference. API

Ruby
SDKper Ruby
Nota

c'è altro da fare. GitHub Trova l'esempio completo e scopri come configurare ed eseguire in AWS Repository di esempi di codice.

# Deletes the objects in an Amazon S3 bucket and deletes the bucket. # # @param bucket [Aws::S3::Bucket] The bucket to empty and delete. def delete_bucket(bucket) puts("\nDo you want to delete all of the objects as well as the bucket (y/n)? ") answer = gets.chomp.downcase if answer == "y" bucket.objects.batch_delete! bucket.delete puts("Emptied and deleted bucket #{bucket.name}.\n") end rescue Aws::Errors::ServiceError => e puts("Couldn't empty and delete bucket #{bucket.name}.") puts("\t#{e.code}: #{e.message}") raise end
  • Per API i dettagli, vedere DeleteBucketin AWS SDK for Ruby APIRiferimento.

Rust
SDKper Rust
Nota

c'è altro da fare GitHub. Trova l'esempio completo e scopri come configurare ed eseguire in AWS Repository di esempi di codice.

pub async fn delete_bucket( client: &aws_sdk_s3::Client, bucket_name: &str, ) -> Result<(), S3ExampleError> { let resp = client.delete_bucket().bucket(bucket_name).send().await; match resp { Ok(_) => Ok(()), Err(err) => { if err .as_service_error() .and_then(aws_sdk_s3::error::ProvideErrorMetadata::code) == Some("NoSuchBucket") { Ok(()) } else { Err(S3ExampleError::from(err)) } } } }
  • Per API i dettagli, vedere DeleteBucketin AWS SDKper API riferimento a Rust.

SAP ABAP
SDKper SAP ABAP
Nota

C'è altro da fare GitHub. Trova l'esempio completo e scopri come configurare ed eseguire in AWS Repository di esempi di codice.

TRY. lo_s3->deletebucket( iv_bucket = iv_bucket_name ). MESSAGE 'Deleted S3 bucket.' TYPE 'I'. CATCH /aws1/cx_s3_nosuchbucket. MESSAGE 'Bucket does not exist.' TYPE 'E'. ENDTRY.
  • Per API i dettagli, vedere DeleteBucketin AWS SDKper SAP ABAP API riferimento.

Swift
SDKper Swift
Nota

c'è altro da fare. GitHub Trova l'esempio completo e scopri come configurare ed eseguire in AWS Repository di esempi di codice.

import AWSS3 public func deleteBucket(name: String) async throws { let input = DeleteBucketInput( bucket: name ) do { _ = try await client.deleteBucket(input: input) } catch { print("ERROR: ", dump(error, name: "Deleting a bucket")) throw error } }
  • Per API i dettagli, vedere DeleteBucketin AWS SDKper API riferimento a Swift.

Per un elenco completo di AWS SDKguide per sviluppatori ed esempi di codice, vediUtilizzo di questo servizio con un SDK AWS. Questo argomento include anche informazioni su come iniziare e dettagli sulle SDK versioni precedenti.