搭PutObjectRetention配 AWS 開發套件或 CLI 使用 - AWS SDK 程式碼範例

AWS 文件 AWS SDK 範例 GitHub 存放庫中提供了更多 SDK 範例

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

PutObjectRetention配 AWS 開發套件或 CLI 使用

下列程式碼範例會示範如何使用PutObjectRetention

動作範例是大型程式的程式碼摘錄,必須在內容中執行。您可以在下列程式碼範例的內容中看到此動作:

.NET
AWS SDK for .NET
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

/// <summary> /// Set or modify a retention period 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="retention">The retention mode.</param> /// <param name="retainUntilDate">The date retention expires.</param> /// <returns>True if successful.</returns> public async Task<bool> ModifyObjectRetentionPeriod(string bucketName, string objectKey, ObjectLockRetentionMode retention, DateTime retainUntilDate) { try { var request = new PutObjectRetentionRequest() { BucketName = bucketName, Key = objectKey, Retention = new ObjectLockRetention() { Mode = retention, RetainUntilDate = retainUntilDate } }; var response = await _amazonS3.PutObjectRetentionAsync(request); Console.WriteLine($"\tSet retention for {objectKey} in {bucketName} until {retainUntilDate:d}."); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; } catch (AmazonS3Exception ex) { Console.WriteLine($"\tError modifying retention period: '{ex.Message}'"); return false; } }
  • 如需 API 詳細資訊,請參閱 AWS SDK for .NET API 參考PutObjectRetention中的。

CLI
AWS CLI

若要設定物件的物件保留組態

下列put-object-retention範例會設定指定物件的物件保留組態,直到 2025-01-01 為止。

aws s3api put-object-retention \ --bucket my-bucket-with-object-lock \ --key doc1.rtf \ --retention '{ "Mode": "GOVERNANCE", "RetainUntilDate": "2025-01-01T00:00:00" }'

此命令不會產生輸出。

Go
SDK for Go V2
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

// S3Actions wraps S3 service actions. type S3Actions struct { S3Client *s3.Client S3Manager *manager.Uploader } // PutObjectRetention sets the object retention configuration for an S3 object. func (actor S3Actions) PutObjectRetention(ctx context.Context, bucket string, key string, retentionMode types.ObjectLockRetentionMode, retentionPeriodDays int32) error { input := &s3.PutObjectRetentionInput{ Bucket: aws.String(bucket), Key: aws.String(key), Retention: &types.ObjectLockRetention{ Mode: retentionMode, RetainUntilDate: aws.Time(time.Now().AddDate(0, 0, int(retentionPeriodDays))), }, BypassGovernanceRetention: aws.Bool(true), } _, err := actor.S3Client.PutObjectRetention(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 }
  • 如需 API 詳細資訊,請參閱 AWS SDK for Go API 參考PutObjectRetention中的。

Java
適用於 Java 2.x 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

// Set or modify a retention period on an object in an S3 bucket. public void modifyObjectRetentionPeriod(String bucketName, String objectKey) { // Calculate the instant one day from now. Instant futureInstant = Instant.now().plus(1, ChronoUnit.DAYS); // Convert the Instant to a ZonedDateTime object with a specific time zone. ZonedDateTime zonedDateTime = futureInstant.atZone(ZoneId.systemDefault()); // Define a formatter for human-readable output. DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); // Format the ZonedDateTime object to a human-readable date string. String humanReadableDate = formatter.format(zonedDateTime); // Print the formatted date string. System.out.println("Formatted Date: " + humanReadableDate); ObjectLockRetention retention = ObjectLockRetention.builder() .mode(ObjectLockRetentionMode.GOVERNANCE) .retainUntilDate(futureInstant) .build(); PutObjectRetentionRequest retentionRequest = PutObjectRetentionRequest.builder() .bucket(bucketName) .key(objectKey) .retention(retention) .build(); getClient().putObjectRetention(retentionRequest); System.out.println("Set retention for "+objectKey +" in " +bucketName +" until "+ humanReadableDate +"."); }
  • 如需 API 詳細資訊,請參閱 AWS SDK for Java 2.x API 參考PutObjectRetention中的。

JavaScript
適用於 JavaScript (v3) 的開發套件
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; import { PutObjectRetentionCommand, 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 PutObjectRetentionCommand({ Bucket: bucketName, Key: objectKey, BypassGovernanceRetention: false, // ChecksumAlgorithm: "ALGORITHM", // ContentMD5: "MD5_HASH", // ExpectedBucketOwner: "ACCOUNT_ID", // RequestPayer: "requester", Retention: { Mode: "GOVERNANCE", // or "COMPLIANCE" RetainUntilDate: new Date(new Date().getTime() + 24 * 60 * 60 * 1000), }, // VersionId: "OBJECT_VERSION_ID", }); try { const response = await client.send(command); console.log( `Object Retention settings updated: ${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"); }
  • 如需 API 詳細資訊,請參閱 AWS SDK for JavaScript API 參考PutObjectRetention中的。

PowerShell
適用的工具 PowerShell

範例 1:此命令會針對指定 S3 儲存貯體中的 'testfile.txt' 物件啟用治理保留模式,直到 2019 年 12 月 31 日 00:00:00 '為止。

Write-S3ObjectRetention -BucketName 's3buckettesting' -Key 'testfile.txt' -Retention_Mode GOVERNANCE -Retention_RetainUntilDate "2019-12-31T00:00:00"
  • 如需 API 詳細資訊,請參閱AWS Tools for PowerShell 指令程PutObjectRetention式參考中的。