与 AWS SDK或PutObjectRetention一起使用 CLI - AWS SDK代码示例

AWS 文档 AWS SDK示例 GitHub 存储库中还有更多SDK示例

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

与 AWS SDK或PutObjectRetention一起使用 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 年 1 月 1 日的对象保留配置。

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适用于 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
SDK适用于 Java 2.x
注意

还有更多相关信息 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
SDK对于 JavaScript (v3)
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

import { PutObjectRetentionCommand, S3Client, S3ServiceException, } from "@aws-sdk/client-s3"; /** * Place a 24-hour retention period on an object in an Amazon S3 bucket. * @param {{ bucketName: string, key: string }} */ export const main = async ({ bucketName, key }) => { const client = new S3Client({}); const command = new PutObjectRetentionCommand({ Bucket: bucketName, Key: key, BypassGovernanceRetention: false, Retention: { // In governance mode, users can't overwrite or delete an object version // or alter its lock settings unless they have special permissions. With // governance mode, you protect objects against being deleted by most users, // but you can still grant some users permission to alter the retention settings // or delete the objects if necessary. Mode: "GOVERNANCE", RetainUntilDate: new Date(new Date().getTime() + 24 * 60 * 60 * 1000), }, }); try { await client.send(command); console.log("Object Retention settings updated."); } catch (caught) { if ( caught instanceof S3ServiceException && caught.name === "NoSuchBucket" ) { console.error( `Error from S3 while modifying the governance mode and retention period on an object. The bucket doesn't exist.`, ); } else if (caught instanceof S3ServiceException) { console.error( `Error from S3 while modifying the governance mode and retention period on an object. ${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, }, key: { type: "string", required: true, }, }; 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")); } }
  • 有关API详细信息,请参阅 “AWS SDK for JavaScript API参考 PutObjectRetention” 中的。

PowerShell
用于 PowerShell

示例 1:该命令为给定 S3 存储桶中的“testfile.txt”对象启用监管保留模式,直到日期“2019 年 12 月 31 日 00:00:00”。

Write-S3ObjectRetention -BucketName 'amzn-s3-demo-bucket' -Key 'testfile.txt' -Retention_Mode GOVERNANCE -Retention_RetainUntilDate "2019-12-31T00:00:00"
  • 有关API详细信息,请参阅 AWS Tools for PowerShell Cmdlet 参考PutObjectRetention中的。

Python
SDK适用于 Python (Boto3)
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

放置对象保留。

s3_client.put_object_retention( Bucket=bucket, Key=key, VersionId=version_id, Retention={"Mode": "GOVERNANCE", "RetainUntilDate": far_future_date}, BypassGovernanceRetention=True, )
  • 有关API详细信息,请参阅PutObjectRetention中的 AWS SDKPython (Boto3) API 参考。