Use PutObjectLegalHold with an Amazon SDK or CLI - Amazon Simple Storage Service
Services or capabilities described in Amazon Web Services documentation might vary by Region. To see the differences applicable to the China Regions, see Getting Started with Amazon Web Services in China (PDF).

Use PutObjectLegalHold with an Amazon SDK or CLI

The following code examples show how to use PutObjectLegalHold.

Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code example:

.NET
Amazon SDK for .NET
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

/// <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; } }
CLI
Amazon CLI

To apply a Legal Hold to an object

The following put-object-legal-hold example sets a Legal Hold on the object doc1.rtf.

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

This command produces no output.

Java
SDK for Java 2.x
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

// 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 +"."); }

For a complete list of Amazon SDK developer guides and code examples, see Using this service with an Amazon SDK. This topic also includes information about getting started and details about previous SDK versions.