À utiliser DeleteObject avec un AWS SDK ou CLI - Exemples de code de l'AWS SDK

D'autres AWS SDK exemples sont disponibles dans le GitHub dépôt AWS Doc SDK Examples.

Les traductions sont fournies par des outils de traduction automatique. En cas de conflit entre le contenu d'une traduction et celui de la version originale en anglais, la version anglaise prévaudra.

À utiliser DeleteObject avec un AWS SDK ou CLI

Les exemples de code suivants montrent comment utiliserDeleteObject.

Les exemples d’actions sont des extraits de code de programmes de plus grande envergure et doivent être exécutés en contexte. Vous pouvez voir cette action en contexte dans les exemples de code suivants :

.NET
AWS SDK for .NET
Note

Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

Supprimez un objet dans un compartiment S3 non soumis à la gestion des versions.

using System; using System.Threading.Tasks; using Amazon.S3; using Amazon.S3.Model; /// <summary> /// This example shows how to delete an object from a non-versioned Amazon /// Simple Storage Service (Amazon S3) bucket. /// </summary> public class DeleteObject { /// <summary> /// The Main method initializes the necessary variables and then calls /// the DeleteObjectNonVersionedBucketAsync method to delete the object /// named by the keyName parameter. /// </summary> public static async Task Main() { const string bucketName = "amzn-s3-demo-bucket"; const string keyName = "testfile.txt"; // If the Amazon S3 bucket is located in an AWS Region other than the // Region of the default account, define the AWS Region for the // Amazon S3 bucket in your call to the AmazonS3Client constructor. // For example RegionEndpoint.USWest2. IAmazonS3 client = new AmazonS3Client(); await DeleteObjectNonVersionedBucketAsync(client, bucketName, keyName); } /// <summary> /// The DeleteObjectNonVersionedBucketAsync takes care of deleting the /// desired object from the named bucket. /// </summary> /// <param name="client">An initialized Amazon S3 client used to delete /// an object from an Amazon S3 bucket.</param> /// <param name="bucketName">The name of the bucket from which the /// object will be deleted.</param> /// <param name="keyName">The name of the object to delete.</param> public static async Task DeleteObjectNonVersionedBucketAsync(IAmazonS3 client, string bucketName, string keyName) { try { var deleteObjectRequest = new DeleteObjectRequest { BucketName = bucketName, Key = keyName, }; Console.WriteLine($"Deleting object: {keyName}"); await client.DeleteObjectAsync(deleteObjectRequest); Console.WriteLine($"Object: {keyName} deleted from {bucketName}."); } catch (AmazonS3Exception ex) { Console.WriteLine($"Error encountered on server. Message:'{ex.Message}' when deleting an object."); } } }

Supprimez un objet dans un compartiment S3 soumis à la gestion des versions.

using System; using System.Threading.Tasks; using Amazon.S3; using Amazon.S3.Model; /// <summary> /// This example creates an object in an Amazon Simple Storage Service /// (Amazon S3) bucket and then deletes the object version that was /// created. /// </summary> public class DeleteObjectVersion { public static async Task Main() { string bucketName = "amzn-s3-demo-bucket"; string keyName = "verstioned-object.txt"; // If the AWS Region of the default user is different from the AWS // Region of the Amazon S3 bucket, pass the AWS Region of the // bucket region to the Amazon S3 client object's constructor. // Define it like this: // RegionEndpoint bucketRegion = RegionEndpoint.USWest2; IAmazonS3 client = new AmazonS3Client(); await CreateAndDeleteObjectVersionAsync(client, bucketName, keyName); } /// <summary> /// This method creates and then deletes a versioned object. /// </summary> /// <param name="client">The initialized Amazon S3 client object used to /// create and delete the object.</param> /// <param name="bucketName">The name of the Amazon S3 bucket where the /// object will be created and deleted.</param> /// <param name="keyName">The key name of the object to create.</param> public static async Task CreateAndDeleteObjectVersionAsync(IAmazonS3 client, string bucketName, string keyName) { try { // Add a sample object. string versionID = await PutAnObject(client, bucketName, keyName); // Delete the object by specifying an object key and a version ID. DeleteObjectRequest request = new DeleteObjectRequest() { BucketName = bucketName, Key = keyName, VersionId = versionID, }; Console.WriteLine("Deleting an object"); await client.DeleteObjectAsync(request); } catch (AmazonS3Exception ex) { Console.WriteLine($"Error: {ex.Message}"); } } /// <summary> /// This method is used to create the temporary Amazon S3 object. /// </summary> /// <param name="client">The initialized Amazon S3 object which will be used /// to create the temporary Amazon S3 object.</param> /// <param name="bucketName">The name of the Amazon S3 bucket where the object /// will be created.</param> /// <param name="objectKey">The name of the Amazon S3 object co create.</param> /// <returns>The Version ID of the created object.</returns> public static async Task<string> PutAnObject(IAmazonS3 client, string bucketName, string objectKey) { PutObjectRequest request = new PutObjectRequest() { BucketName = bucketName, Key = objectKey, ContentBody = "This is the content body!", }; PutObjectResponse response = await client.PutObjectAsync(request); return response.VersionId; } }
  • Pour API plus de détails, voir DeleteObjectla section AWS SDK for .NET APIRéférence.

Bash
AWS CLI avec le script Bash
Note

Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################### # function delete_item_in_bucket # # This function deletes the specified file from the specified bucket. # # Parameters: # $1 - The name of the bucket. # $2 - The key (file name) in the bucket to delete. # Returns: # 0 - If successful. # 1 - If it fails. ############################################################################### function delete_item_in_bucket() { local bucket_name=$1 local key=$2 local response response=$(aws s3api delete-object \ --bucket "$bucket_name" \ --key "$key") # shellcheck disable=SC2181 if [[ $? -ne 0 ]]; then errecho "ERROR: AWS reports s3api delete-object operation failed.\n$response" return 1 fi }
  • Pour API plus de détails, voir DeleteObjectla section Référence des AWS CLI commandes.

C++
SDKpour C++
Note

Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

bool AwsDoc::S3::deleteObject(const Aws::String &objectKey, const Aws::String &fromBucket, const Aws::S3::S3ClientConfiguration &clientConfig) { Aws::S3::S3Client client(clientConfig); Aws::S3::Model::DeleteObjectRequest request; request.WithKey(objectKey) .WithBucket(fromBucket); Aws::S3::Model::DeleteObjectOutcome outcome = client.DeleteObject(request); if (!outcome.IsSuccess()) { auto err = outcome.GetError(); std::cerr << "Error: deleteObject: " << err.GetExceptionName() << ": " << err.GetMessage() << std::endl; } else { std::cout << "Successfully deleted the object." << std::endl; } return outcome.IsSuccess(); }
  • Pour API plus de détails, voir DeleteObjectla section AWS SDK for C++ APIRéférence.

CLI
AWS CLI

La commande suivante supprime un objet nommé test.txt dans un compartiment nommé my-bucket :

aws s3api delete-object --bucket my-bucket --key test.txt

Si le versionnement des compartiments est activé, la sortie contiendra l'ID de version du marqueur de suppression :

{ "VersionId": "9_gKg5vG56F.TTEUdwkxGpJ3tNDlWlGq", "DeleteMarker": true }

Pour plus d'informations sur la suppression d'objets, consultez Supprimer des objets dans le manuel Amazon S3 Developer Guide.

  • Pour API plus de détails, voir DeleteObjectla section Référence des AWS CLI commandes.

Go
SDKpour Go V2
Note

Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

// S3Actions wraps S3 service actions. type S3Actions struct { S3Client *s3.Client S3Manager *manager.Uploader } // DeleteObject deletes an object from a bucket. func (actor S3Actions) DeleteObject(ctx context.Context, bucket string, key string, versionId string, bypassGovernance bool) (bool, error) { deleted := false input := &s3.DeleteObjectInput{ Bucket: aws.String(bucket), Key: aws.String(key), } if versionId != "" { input.VersionId = aws.String(versionId) } if bypassGovernance { input.BypassGovernanceRetention = aws.Bool(true) } _, err := actor.S3Client.DeleteObject(ctx, input) if err != nil { var noKey *types.NoSuchKey var apiErr *smithy.GenericAPIError if errors.As(err, &noKey) { log.Printf("Object %s does not exist in %s.\n", key, bucket) err = noKey } else if errors.As(err, &apiErr) { switch apiErr.ErrorCode() { case "AccessDenied": log.Printf("Access denied: cannot delete object %s from %s.\n", key, bucket) err = nil case "InvalidArgument": if bypassGovernance { log.Printf("You cannot specify bypass governance on a bucket without lock enabled.") err = nil } } } } else { deleted = true } return deleted, err }
  • Pour API plus de détails, voir DeleteObjectla section AWS SDK for Go APIRéférence.

Java
SDKpour Java 2.x
Note

Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

/** * Deletes an object from an S3 bucket asynchronously. * * @param bucketName the name of the S3 bucket * @param key the key (file name) of the object to be deleted * @return a {@link CompletableFuture} that completes when the object has been deleted */ public CompletableFuture<Void> deleteObjectFromBucketAsync(String bucketName, String key) { DeleteObjectRequest deleteObjectRequest = DeleteObjectRequest.builder() .bucket(bucketName) .key(key) .build(); CompletableFuture<DeleteObjectResponse> response = getAsyncClient().deleteObject(deleteObjectRequest); response.whenComplete((deleteRes, ex) -> { if (deleteRes != null) { logger.info(key + " was deleted"); } else { throw new RuntimeException("An S3 exception occurred during delete", ex); } }); return response.thenApply(r -> null); }
  • Pour API plus de détails, voir DeleteObjectla section AWS SDK for Java 2.x APIRéférence.

JavaScript
SDKpour JavaScript (v3)
Note

Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

Supprimez un objet.

import { DeleteObjectCommand, S3Client, S3ServiceException, waitUntilObjectNotExists, } from "@aws-sdk/client-s3"; /** * Delete one object from an Amazon S3 bucket. * @param {{ bucketName: string, key: string }} */ export const main = async ({ bucketName, key }) => { const client = new S3Client({}); try { await client.send( new DeleteObjectCommand({ Bucket: bucketName, Key: key, }), ); await waitUntilObjectNotExists( { client }, { Bucket: bucketName, Key: key }, ); // A successful delete, or a delete for a non-existent object, both return // a 204 response code. console.log( `The object "${key}" from bucket "${bucketName}" was deleted, or it didn't exist.`, ); } catch (caught) { if ( caught instanceof S3ServiceException && caught.name === "NoSuchBucket" ) { console.error( `Error from S3 while deleting object from ${bucketName}. The bucket doesn't exist.`, ); } else if (caught instanceof S3ServiceException) { console.error( `Error from S3 while deleting object from ${bucketName}. ${caught.name}: ${caught.message}`, ); } else { throw caught; } } };
  • Pour API plus de détails, voir DeleteObjectla section AWS SDK for JavaScript APIRéférence.

PHP
SDK pour PHP
Note

Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

public function deleteObject(string $bucketName, string $fileName, array $args = []) { $parameters = array_merge(['Bucket' => $bucketName, 'Key' => $fileName], $args); try { $this->client->deleteObject($parameters); if ($this->verbose) { echo "Deleted the object named: $fileName from $bucketName.\n"; } } catch (AwsException $exception) { if ($this->verbose) { echo "Failed to delete $fileName from $bucketName with error: {$exception->getMessage()}\n"; echo "Please fix error with object deletion before continuing."; } throw $exception; } }
  • Pour API plus de détails, voir DeleteObjectla section AWS SDK for PHP APIRéférence.

Python
SDKpour Python (Boto3)
Note

Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

Supprimez un objet.

class ObjectWrapper: """Encapsulates S3 object actions.""" def __init__(self, s3_object): """ :param s3_object: A Boto3 Object resource. This is a high-level resource in Boto3 that wraps object actions in a class-like structure. """ self.object = s3_object self.key = self.object.key def delete(self): """ Deletes the object. """ try: self.object.delete() self.object.wait_until_not_exists() logger.info( "Deleted object '%s' from bucket '%s'.", self.object.key, self.object.bucket_name, ) except ClientError: logger.exception( "Couldn't delete object '%s' from bucket '%s'.", self.object.key, self.object.bucket_name, ) raise

Faire revenir un objet à une version antérieure en supprimant les versions ultérieures de l'objet.

def rollback_object(bucket, object_key, version_id): """ Rolls back an object to an earlier version by deleting all versions that occurred after the specified rollback version. Usage is shown in the usage_demo_single_object function at the end of this module. :param bucket: The bucket that holds the object to roll back. :param object_key: The object to roll back. :param version_id: The version ID to roll back to. """ # Versions must be sorted by last_modified date because delete markers are # at the end of the list even when they are interspersed in time. versions = sorted( bucket.object_versions.filter(Prefix=object_key), key=attrgetter("last_modified"), reverse=True, ) logger.debug( "Got versions:\n%s", "\n".join( [ f"\t{version.version_id}, last modified {version.last_modified}" for version in versions ] ), ) if version_id in [ver.version_id for ver in versions]: print(f"Rolling back to version {version_id}") for version in versions: if version.version_id != version_id: version.delete() print(f"Deleted version {version.version_id}") else: break print(f"Active version is now {bucket.Object(object_key).version_id}") else: raise KeyError( f"{version_id} was not found in the list of versions for " f"{object_key}." )

Faire revenir un objet supprimé en supprimant le marqueur de suppression actif de l'objet.

def revive_object(bucket, object_key): """ Revives a versioned object that was deleted by removing the object's active delete marker. A versioned object presents as deleted when its latest version is a delete marker. By removing the delete marker, we make the previous version the latest version and the object then presents as *not* deleted. Usage is shown in the usage_demo_single_object function at the end of this module. :param bucket: The bucket that contains the object. :param object_key: The object to revive. """ # Get the latest version for the object. response = s3.meta.client.list_object_versions( Bucket=bucket.name, Prefix=object_key, MaxKeys=1 ) if "DeleteMarkers" in response: latest_version = response["DeleteMarkers"][0] if latest_version["IsLatest"]: logger.info( "Object %s was indeed deleted on %s. Let's revive it.", object_key, latest_version["LastModified"], ) obj = bucket.Object(object_key) obj.Version(latest_version["VersionId"]).delete() logger.info( "Revived %s, active version is now %s with body '%s'", object_key, obj.version_id, obj.get()["Body"].read(), ) else: logger.warning( "Delete marker is not the latest version for %s!", object_key ) elif "Versions" in response: logger.warning("Got an active version for %s, nothing to do.", object_key) else: logger.error("Couldn't get any version info for %s.", object_key)

Créez un gestionnaire Lambda qui supprime un marqueur de suppression d'un objet S3. Ce gestionnaire peut être utilisé pour nettoyer efficacement les marqueurs de suppression superflus dans un compartiment soumis au contrôle de version.

import logging from urllib import parse import boto3 from botocore.exceptions import ClientError logger = logging.getLogger(__name__) logger.setLevel("INFO") s3 = boto3.client("s3") def lambda_handler(event, context): """ Removes a delete marker from the specified versioned object. :param event: The S3 batch event that contains the ID of the delete marker to remove. :param context: Context about the event. :return: A result structure that Amazon S3 uses to interpret the result of the operation. When the result code is TemporaryFailure, S3 retries the operation. """ # Parse job parameters from Amazon S3 batch operations invocation_id = event["invocationId"] invocation_schema_version = event["invocationSchemaVersion"] results = [] result_code = None result_string = None task = event["tasks"][0] task_id = task["taskId"] try: obj_key = parse.unquote(task["s3Key"], encoding="utf-8") obj_version_id = task["s3VersionId"] bucket_name = task["s3BucketArn"].split(":")[-1] logger.info( "Got task: remove delete marker %s from object %s.", obj_version_id, obj_key ) try: # If this call does not raise an error, the object version is not a delete # marker and should not be deleted. response = s3.head_object( Bucket=bucket_name, Key=obj_key, VersionId=obj_version_id ) result_code = "PermanentFailure" result_string = ( f"Object {obj_key}, ID {obj_version_id} is not " f"a delete marker." ) logger.debug(response) logger.warning(result_string) except ClientError as error: delete_marker = error.response["ResponseMetadata"]["HTTPHeaders"].get( "x-amz-delete-marker", "false" ) if delete_marker == "true": logger.info( "Object %s, version %s is a delete marker.", obj_key, obj_version_id ) try: s3.delete_object( Bucket=bucket_name, Key=obj_key, VersionId=obj_version_id ) result_code = "Succeeded" result_string = ( f"Successfully removed delete marker " f"{obj_version_id} from object {obj_key}." ) logger.info(result_string) except ClientError as error: # Mark request timeout as a temporary failure so it will be retried. if error.response["Error"]["Code"] == "RequestTimeout": result_code = "TemporaryFailure" result_string = ( f"Attempt to remove delete marker from " f"object {obj_key} timed out." ) logger.info(result_string) else: raise else: raise ValueError( f"The x-amz-delete-marker header is either not " f"present or is not 'true'." ) except Exception as error: # Mark all other exceptions as permanent failures. result_code = "PermanentFailure" result_string = str(error) logger.exception(error) finally: results.append( { "taskId": task_id, "resultCode": result_code, "resultString": result_string, } ) return { "invocationSchemaVersion": invocation_schema_version, "treatMissingKeysAs": "PermanentFailure", "invocationId": invocation_id, "results": results, }
  • Pour API plus de détails, reportez-vous DeleteObjectà la section AWS SDKrelative à la référence Python (Boto3). API

Rust
SDKpour Rust
Note

Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

/// Delete an object from a bucket. pub async fn remove_object( client: &aws_sdk_s3::Client, bucket: &str, key: &str, ) -> Result<(), S3ExampleError> { client .delete_object() .bucket(bucket) .key(key) .send() .await?; // There are no modeled errors to handle when deleting an object. Ok(()) }
  • Pour API plus de détails, reportez-vous DeleteObjectà la section AWS SDKpour la API référence à Rust.

SAP ABAP
SDKpour SAP ABAP
Note

Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

TRY. lo_s3->deleteobject( iv_bucket = iv_bucket_name iv_key = iv_object_key ). MESSAGE 'Object deleted from S3 bucket.' TYPE 'I'. CATCH /aws1/cx_s3_nosuchbucket. MESSAGE 'Bucket does not exist.' TYPE 'E'. ENDTRY.
  • Pour API plus de détails, voir DeleteObject AWSSDKpour SAP ABAP API référence.

Swift
SDKpour Swift
Note

Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

import AWSS3 public func deleteFile(bucket: String, key: String) async throws { let input = DeleteObjectInput( bucket: bucket, key: key ) do { _ = try await client.deleteObject(input: input) } catch { print("ERROR: ", dump(error, name: "Deleting a file.")) throw error } }
  • Pour API plus de détails, reportez-vous DeleteObjectà AWS SDKla section dédiée à Swift API.