Gunakan PutObjectLegalHold dengan AWS SDK atau CLI - AWS SDKContoh Kode

Ada lebih banyak AWS SDK contoh yang tersedia di GitHub repo SDKContoh AWS Dokumen.

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

Gunakan PutObjectLegalHold dengan AWS SDK atau CLI

Contoh kode berikut menunjukkan cara menggunakanPutObjectLegalHold.

Contoh tindakan adalah kutipan kode dari program yang lebih besar dan harus dijalankan dalam konteks. Anda dapat melihat tindakan ini dalam konteks dalam contoh kode berikut:

.NET
AWS SDK for .NET
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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; } }
CLI
AWS CLI

Untuk menerapkan Penahanan Hukum pada suatu objek

put-object-legal-holdContoh berikut menetapkan Penahanan Hukum pada objekdoc1.rtf.

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

Perintah ini tidak menghasilkan output.

Go
SDKuntuk Go V2
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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 }
Java
SDKuntuk Java 2.x
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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 +"."); }
JavaScript
SDKuntuk JavaScript (v3)
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

import { PutObjectLegalHoldCommand, S3Client, S3ServiceException, } from "@aws-sdk/client-s3"; /** * Apply a legal hold configuration to the specified object. * @param {{ bucketName: string, objectKey: string, legalHoldStatus: "ON" | "OFF" }} */ export const main = async ({ bucketName, objectKey, legalHoldStatus }) => { if (!["OFF", "ON"].includes(legalHoldStatus.toUpperCase())) { throw new Error( "Invalid parameter. legalHoldStatus must be 'ON' or 'OFF'.", ); } const client = new S3Client({}); 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: legalHoldStatus, }, }); try { await client.send(command); console.log( `Legal hold status set to "${legalHoldStatus}" for "${objectKey}" in "${bucketName}"`, ); } catch (caught) { if ( caught instanceof S3ServiceException && caught.name === "NoSuchBucket" ) { console.error( `Error from S3 while modifying legal hold status for "${objectKey}" in "${bucketName}". The bucket doesn't exist.`, ); } else if (caught instanceof S3ServiceException) { console.error( `Error from S3 while modifying legal hold status for "${objectKey}" in "${bucketName}". ${caught.name}: ${caught.message}`, ); } else { throw caught; } } }; // Call function if run directly import { parseArgs } from "node:util"; import { isMain, validateArgs, } from "@aws-doc-sdk-examples/lib/utils/util-node.js"; const loadArgs = () => { const options = { bucketName: { type: "string", required: true, }, objectKey: { type: "string", required: true, }, legalHoldStatus: { type: "string", default: "ON", }, }; const results = parseArgs({ options }); const { errors } = validateArgs({ options }, results); return { errors, results }; }; if (isMain(import.meta.url)) { const { errors, results } = loadArgs(); if (!errors) { main(results.values); } else { console.error(errors.join("\n")); } }
Python
SDKuntuk Python (Boto3)
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

Letakkan benda penahanan hukum.

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 )