À utiliser PutObjectLegalHold 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 PutObjectLegalHold avec un AWS SDK ou CLI

Les exemples de code suivants montrent comment utiliserPutObjectLegalHold.

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 l’exemple de code suivant :

.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.

/// <summary> /// Set or modify a legal hold on an object in an S3 bucket. /// </summary> /// <param name="bucketName">The bucket of the object.</param> /// <param name="objectKey">The key of the object.</param> /// <param name="holdStatus">The On or Off status for the legal hold.</param> /// <returns>True if successful.</returns> public async Task<bool> ModifyObjectLegalHold(string bucketName, string objectKey, ObjectLockLegalHoldStatus holdStatus) { try { var request = new PutObjectLegalHoldRequest() { BucketName = bucketName, Key = objectKey, LegalHold = new ObjectLockLegalHold() { Status = holdStatus } }; var response = await _amazonS3.PutObjectLegalHoldAsync(request); Console.WriteLine($"\tModified legal hold for {objectKey} in {bucketName}."); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; } catch (AmazonS3Exception ex) { Console.WriteLine($"\tError modifying legal hold: '{ex.Message}'"); return false; } }
  • Pour API plus de détails, voir PutObjectLegalHoldla section AWS SDK for .NET APIRéférence.

CLI
AWS CLI

Pour appliquer une suspension légale à un objet

L'put-object-legal-holdexemple suivant définit une conservation légale sur l'objetdoc1.rtf.

aws s3api put-object-legal-hold \ --bucket my-bucket-with-object-lock \ --key doc1.rtf \ --legal-hold Status=ON

Cette commande ne produit aucun résultat.

  • Pour API plus de détails, voir PutObjectLegalHoldla 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 } // PutObjectLegalHold sets the legal hold configuration for an S3 object. func (actor S3Actions) PutObjectLegalHold(ctx context.Context, bucket string, key string, versionId string, legalHoldStatus types.ObjectLockLegalHoldStatus) error { input := &s3.PutObjectLegalHoldInput{ Bucket: aws.String(bucket), Key: aws.String(key), LegalHold: &types.ObjectLockLegalHold{ Status: legalHoldStatus, }, } if versionId != "" { input.VersionId = aws.String(versionId) } _, err := actor.S3Client.PutObjectLegalHold(ctx, input) if err != nil { var noKey *types.NoSuchKey if errors.As(err, &noKey) { log.Printf("Object %s does not exist in bucket %s.\n", key, bucket) err = noKey } } return err }
  • Pour API plus de détails, voir PutObjectLegalHoldla 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.

// Set or modify a legal hold on an object in an S3 bucket. public void modifyObjectLegalHold(String bucketName, String objectKey, boolean legalHoldOn) { ObjectLockLegalHold legalHold ; if (legalHoldOn) { legalHold = ObjectLockLegalHold.builder() .status(ObjectLockLegalHoldStatus.ON) .build(); } else { legalHold = ObjectLockLegalHold.builder() .status(ObjectLockLegalHoldStatus.OFF) .build(); } PutObjectLegalHoldRequest legalHoldRequest = PutObjectLegalHoldRequest.builder() .bucket(bucketName) .key(objectKey) .legalHold(legalHold) .build(); getClient().putObjectLegalHold(legalHoldRequest) ; System.out.println("Modified legal hold for "+ objectKey +" in "+bucketName +"."); }
  • Pour API plus de détails, voir PutObjectLegalHoldla 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.

import { fileURLToPath } from "url"; import { PutObjectLegalHoldCommand, S3Client } from "@aws-sdk/client-s3"; /** * @param {S3Client} client * @param {string} bucketName * @param {string} objectKey */ export const main = async (client, bucketName, objectKey) => { const command = new PutObjectLegalHoldCommand({ Bucket: bucketName, Key: objectKey, LegalHold: { // Set the status to 'ON' to place a legal hold on the object. // Set the status to 'OFF' to remove the legal hold. Status: "ON", }, // Optionally, you can provide additional parameters // ChecksumAlgorithm: "ALGORITHM", // ContentMD5: "MD5_HASH", // ExpectedBucketOwner: "ACCOUNT_ID", // RequestPayer: "requester", // VersionId: "OBJECT_VERSION_ID", }); try { const response = await client.send(command); console.log( `Object legal hold status: ${response.$metadata.httpStatusCode}`, ); } catch (err) { console.error(err); } }; // Invoke main function if this file was run directly. if (process.argv[1] === fileURLToPath(import.meta.url)) { main(new S3Client(), "BUCKET_NAME", "OBJECT_KEY"); }
  • Pour API plus de détails, voir PutObjectLegalHoldla section AWS SDK for JavaScript 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.

Mettez un objet en détention légale.

def set_legal_hold(s3_client, bucket: str, key: str) -> None: """ Set a legal hold on a specific file in a bucket. Args: s3_client: Boto3 S3 client. bucket: The name of the bucket containing the file. key: The key of the file to set the legal hold on. """ print() logger.info("Setting legal hold on file [%s] in bucket [%s]", key, bucket) try: before_status = "OFF" after_status = "ON" s3_client.put_object_legal_hold( Bucket=bucket, Key=key, LegalHold={"Status": after_status} ) logger.debug( "Legal hold set successfully on file [%s] in bucket [%s]", key, bucket ) _print_legal_hold_update(bucket, key, before_status, after_status) except Exception as e: logger.error( "Failed to set legal hold on file [%s] in bucket [%s]: %s", key, bucket, e )
  • Pour API plus de détails, reportez-vous PutObjectLegalHoldà la section AWS SDKrelative à la référence Python (Boto3). API