将 PutObjectLockConfiguration 与 Amazon SDK 或 CLI 配合使用 - Amazon Simple Storage Service
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

PutObjectLockConfiguration 与 Amazon SDK 或 CLI 配合使用

以下代码示例演示如何使用 PutObjectLockConfiguration

操作示例是大型程序的代码摘录,必须在上下文中运行。在以下代码示例中,您可以查看此操作的上下文:

.NET
Amazon SDK for .NET
注意

查看 GitHub,了解更多信息。例如,如果您将大小为 128 KB 到 1024 KB 的对象设置为从 S3 标准存储类移到 S3标准-IA 存储类,则大小精确为 1024 KB 和 128 KB 的对象将不会转换到 S3 标准-IA。

设置存储桶的对象锁定配置。

/// <summary> /// Enable object lock on an existing bucket. /// </summary> /// <param name="bucketName">The name of the bucket to modify.</param> /// <returns>True if successful.</returns> public async Task<bool> EnableObjectLockOnBucket(string bucketName) { try { // First, enable Versioning on the bucket. await _amazonS3.PutBucketVersioningAsync(new PutBucketVersioningRequest() { BucketName = bucketName, VersioningConfig = new S3BucketVersioningConfig() { EnableMfaDelete = false, Status = VersionStatus.Enabled } }); var request = new PutObjectLockConfigurationRequest() { BucketName = bucketName, ObjectLockConfiguration = new ObjectLockConfiguration() { ObjectLockEnabled = new ObjectLockEnabled("Enabled"), }, }; var response = await _amazonS3.PutObjectLockConfigurationAsync(request); Console.WriteLine($"\tAdded an object lock policy to bucket {bucketName}."); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; } catch (AmazonS3Exception ex) { Console.WriteLine($"Error modifying object lock: '{ex.Message}'"); return false; } }

设置存储桶的默认保留期。

/// <summary> /// Set or modify a retention period on an S3 bucket. /// </summary> /// <param name="bucketName">The bucket to modify.</param> /// <param name="retention">The retention mode.</param> /// <param name="retainUntilDate">The date for retention until.</param> /// <returns>True if successful.</returns> public async Task<bool> ModifyBucketDefaultRetention(string bucketName, bool enableObjectLock, ObjectLockRetentionMode retention, DateTime retainUntilDate) { var enabledString = enableObjectLock ? "Enabled" : "Disabled"; var timeDifference = retainUntilDate.Subtract(DateTime.Now); try { // First, enable Versioning on the bucket. await _amazonS3.PutBucketVersioningAsync(new PutBucketVersioningRequest() { BucketName = bucketName, VersioningConfig = new S3BucketVersioningConfig() { EnableMfaDelete = false, Status = VersionStatus.Enabled } }); var request = new PutObjectLockConfigurationRequest() { BucketName = bucketName, ObjectLockConfiguration = new ObjectLockConfiguration() { ObjectLockEnabled = new ObjectLockEnabled(enabledString), Rule = new ObjectLockRule() { DefaultRetention = new DefaultRetention() { Mode = retention, Days = timeDifference.Days // Can be specified in days or years but not both. } } } }; var response = await _amazonS3.PutObjectLockConfigurationAsync(request); Console.WriteLine($"\tAdded a default retention to bucket {bucketName}."); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; } catch (AmazonS3Exception ex) { Console.WriteLine($"\tError modifying object lock: '{ex.Message}'"); return false; } }
CLI
Amazon CLI

在存储桶上设置对象锁定配置

以下 put-object-lock-configuration 示例在指定存储桶上设置了 50 天的对象锁定。

aws s3api put-object-lock-configuration \ --bucket my-bucket-with-object-lock \ --object-lock-configuration '{ "ObjectLockEnabled": "Enabled", "Rule": { "DefaultRetention": { "Mode": "COMPLIANCE", "Days": 50 }}}'

此命令不生成任何输出。

Go
适用于 Go V2 的 SDK
注意

查看 GitHub,了解更多信息。例如,如果您将大小为 128 KB 到 1024 KB 的对象设置为从 S3 标准存储类移到 S3标准-IA 存储类,则大小精确为 1024 KB 和 128 KB 的对象将不会转换到 S3 标准-IA。

设置存储桶的对象锁定配置。

// S3Actions wraps S3 service actions. type S3Actions struct { S3Client *s3.Client S3Manager *manager.Uploader } // EnableObjectLockOnBucket enables object locking on an existing bucket. func (actor S3Actions) EnableObjectLockOnBucket(ctx context.Context, bucket string) error { // Versioning must be enabled on the bucket before object locking is enabled. verInput := &s3.PutBucketVersioningInput{ Bucket: aws.String(bucket), VersioningConfiguration: &types.VersioningConfiguration{ MFADelete: types.MFADeleteDisabled, Status: types.BucketVersioningStatusEnabled, }, } _, err := actor.S3Client.PutBucketVersioning(ctx, verInput) if err != nil { var noBucket *types.NoSuchBucket if errors.As(err, &noBucket) { log.Printf("Bucket %s does not exist.\n", bucket) err = noBucket } return err } input := &s3.PutObjectLockConfigurationInput{ Bucket: aws.String(bucket), ObjectLockConfiguration: &types.ObjectLockConfiguration{ ObjectLockEnabled: types.ObjectLockEnabledEnabled, }, } _, err = actor.S3Client.PutObjectLockConfiguration(ctx, input) if err != nil { var noBucket *types.NoSuchBucket if errors.As(err, &noBucket) { log.Printf("Bucket %s does not exist.\n", bucket) err = noBucket } } return err }

设置存储桶的默认保留期。

// S3Actions wraps S3 service actions. type S3Actions struct { S3Client *s3.Client S3Manager *manager.Uploader } // ModifyDefaultBucketRetention modifies the default retention period of an existing bucket. func (actor S3Actions) ModifyDefaultBucketRetention( ctx context.Context, bucket string, lockMode types.ObjectLockEnabled, retentionPeriod int32, retentionMode types.ObjectLockRetentionMode) error { input := &s3.PutObjectLockConfigurationInput{ Bucket: aws.String(bucket), ObjectLockConfiguration: &types.ObjectLockConfiguration{ ObjectLockEnabled: lockMode, Rule: &types.ObjectLockRule{ DefaultRetention: &types.DefaultRetention{ Days: aws.Int32(retentionPeriod), Mode: retentionMode, }, }, }, } _, err := actor.S3Client.PutObjectLockConfiguration(ctx, input) if err != nil { var noBucket *types.NoSuchBucket if errors.As(err, &noBucket) { log.Printf("Bucket %s does not exist.\n", bucket) err = noBucket } } return err }
Java
SDK for Java 2.x
注意

查看 GitHub,了解更多信息。例如,如果您将大小为 128 KB 到 1024 KB 的对象设置为从 S3 标准存储类移到 S3标准-IA 存储类,则大小精确为 1024 KB 和 128 KB 的对象将不会转换到 S3 标准-IA。

设置存储桶的对象锁定配置。

// Enable object lock on an existing bucket. public void enableObjectLockOnBucket(String bucketName) { try { VersioningConfiguration versioningConfiguration = VersioningConfiguration.builder() .status(BucketVersioningStatus.ENABLED) .build(); PutBucketVersioningRequest putBucketVersioningRequest = PutBucketVersioningRequest.builder() .bucket(bucketName) .versioningConfiguration(versioningConfiguration) .build(); // Enable versioning on the bucket. getClient().putBucketVersioning(putBucketVersioningRequest); PutObjectLockConfigurationRequest request = PutObjectLockConfigurationRequest.builder() .bucket(bucketName) .objectLockConfiguration(ObjectLockConfiguration.builder() .objectLockEnabled(ObjectLockEnabled.ENABLED) .build()) .build(); getClient().putObjectLockConfiguration(request); System.out.println("Successfully enabled object lock on "+bucketName); } catch (S3Exception ex) { System.out.println("Error modifying object lock: '" + ex.getMessage() + "'"); } }

设置存储桶的默认保留期。

// Set or modify a retention period on an S3 bucket. public void modifyBucketDefaultRetention(String bucketName) { VersioningConfiguration versioningConfiguration = VersioningConfiguration.builder() .mfaDelete(MFADelete.DISABLED) .status(BucketVersioningStatus.ENABLED) .build(); PutBucketVersioningRequest versioningRequest = PutBucketVersioningRequest.builder() .bucket(bucketName) .versioningConfiguration(versioningConfiguration) .build(); getClient().putBucketVersioning(versioningRequest); DefaultRetention rention = DefaultRetention.builder() .days(1) .mode(ObjectLockRetentionMode.GOVERNANCE) .build(); ObjectLockRule lockRule = ObjectLockRule.builder() .defaultRetention(rention) .build(); ObjectLockConfiguration objectLockConfiguration = ObjectLockConfiguration.builder() .objectLockEnabled(ObjectLockEnabled.ENABLED) .rule(lockRule) .build(); PutObjectLockConfigurationRequest putObjectLockConfigurationRequest = PutObjectLockConfigurationRequest.builder() .bucket(bucketName) .objectLockConfiguration(objectLockConfiguration) .build(); getClient().putObjectLockConfiguration(putObjectLockConfigurationRequest) ; System.out.println("Added a default retention to bucket "+bucketName +"."); }
JavaScript
适用于 JavaScript 的 SDK(v3)
注意

查看 GitHub,了解更多信息。例如,如果您将大小为 128 KB 到 1024 KB 的对象设置为从 S3 标准存储类移到 S3标准-IA 存储类,则大小精确为 1024 KB 和 128 KB 的对象将不会转换到 S3 标准-IA。

设置存储桶的对象锁定配置。

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; import { PutObjectLockConfigurationCommand, S3Client, } from "@aws-sdk/client-s3"; /** * @param {S3Client} client * @param {string} bucketName */ export const main = async (client, bucketName) => { const command = new PutObjectLockConfigurationCommand({ Bucket: bucketName, // The Object Lock configuration that you want to apply to the specified bucket. ObjectLockConfiguration: { ObjectLockEnabled: "Enabled", }, // Optionally, you can provide additional parameters // ExpectedBucketOwner: "ACCOUNT_ID", // RequestPayer: "requester", // Token: "OPTIONAL_TOKEN", }); try { const response = await client.send(command); console.log( `Object Lock Configuration 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"); }

设置存储桶的默认保留期。

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; import { PutObjectLockConfigurationCommand, S3Client, } from "@aws-sdk/client-s3"; /** * @param {S3Client} client * @param {string} bucketName */ export const main = async (client, bucketName) => { const command = new PutObjectLockConfigurationCommand({ Bucket: bucketName, // The Object Lock configuration that you want to apply to the specified bucket. ObjectLockConfiguration: { ObjectLockEnabled: "Enabled", Rule: { DefaultRetention: { Mode: "GOVERNANCE", Years: 3, }, }, }, // Optionally, you can provide additional parameters // ExpectedBucketOwner: "ACCOUNT_ID", // RequestPayer: "requester", // Token: "OPTIONAL_TOKEN", }); try { const response = await client.send(command); console.log( `Default Object Lock Configuration 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"); }

有关 Amazon SDK 开发人员指南和代码示例的完整列表,请参阅 将此服务与 Amazon SDK 结合使用。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。