AWS SDK 또는 CLI와 함께 PutObjectRetention 사용 - Amazon Simple Storage Service

AWS SDK 또는 CLI와 함께 PutObjectRetention 사용

다음 코드 예제는 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
SDK for 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 for 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 Cmdlet 참조의 PutObjectRetention을 참조하세요.

AWS SDK 개발자 가이드 및 코드 예시의 전체 목록은 AWS SDK와 함께 이 서비스 사용 단원을 참조하세요. 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.