또는 와 PutBucketLifecycleConfigurationAWS SDK 함께 사용 CLI - AWS SDK 코드 예제

AWS 문서 예제 리포지토리에서 더 많은 SDK GitHub AWS SDK 예제를 사용할 수 있습니다.

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

또는 와 PutBucketLifecycleConfigurationAWS SDK 함께 사용 CLI

다음 코드 예제는 PutBucketLifecycleConfiguration의 사용 방법을 보여 줍니다.

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.

.NET
AWS SDK for .NET
참고

에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

/// <summary> /// Adds lifecycle configuration information to the S3 bucket named in /// the bucketName parameter. /// </summary> /// <param name="client">The S3 client used to call the /// PutLifecycleConfigurationAsync method.</param> /// <param name="bucketName">A string representing the S3 bucket to /// which configuration information will be added.</param> /// <param name="configuration">A LifecycleConfiguration object that /// will be applied to the S3 bucket.</param> public static async Task AddExampleLifecycleConfigAsync(IAmazonS3 client, string bucketName, LifecycleConfiguration configuration) { var request = new PutLifecycleConfigurationRequest() { BucketName = bucketName, Configuration = configuration, }; var response = await client.PutLifecycleConfigurationAsync(request); }
CLI
AWS CLI

다음 명령은 my-bucket이라는 버킷에 수명 주기 구성을 적용합니다.

aws s3api put-bucket-lifecycle-configuration --bucket my-bucket --lifecycle-configuration file://lifecycle.json

파일은 현재 폴더의 JSON 문서lifecycle.json로, 두 가지 규칙을 지정합니다.

{ "Rules": [ { "ID": "Move rotated logs to Glacier", "Prefix": "rotated/", "Status": "Enabled", "Transitions": [ { "Date": "2015-11-10T00:00:00.000Z", "StorageClass": "GLACIER" } ] }, { "Status": "Enabled", "Prefix": "", "NoncurrentVersionTransitions": [ { "NoncurrentDays": 2, "StorageClass": "GLACIER" } ], "ID": "Move old versions to Glacier" } ] }

첫 번째 규칙은 rotated 접두사가 있는 파일을 지정된 날짜에 Glacier로 옮깁니다. 두 번째 규칙은 이전 객체 버전이 더 이상 최신 버전이 아닌 경우 Glacier로 옮깁니다. 허용되는 타임스탬프 형식에 대한 자세한 내용은 AWS CLI 사용 설명서의 파라미터 값 지정을 참조하세요.

Java
SDK Java 2.x용
참고

에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.LifecycleRuleFilter; import software.amazon.awssdk.services.s3.model.Transition; import software.amazon.awssdk.services.s3.model.GetBucketLifecycleConfigurationRequest; import software.amazon.awssdk.services.s3.model.GetBucketLifecycleConfigurationResponse; import software.amazon.awssdk.services.s3.model.DeleteBucketLifecycleRequest; import software.amazon.awssdk.services.s3.model.TransitionStorageClass; import software.amazon.awssdk.services.s3.model.LifecycleRule; import software.amazon.awssdk.services.s3.model.ExpirationStatus; import software.amazon.awssdk.services.s3.model.BucketLifecycleConfiguration; import software.amazon.awssdk.services.s3.model.PutBucketLifecycleConfigurationRequest; import software.amazon.awssdk.services.s3.model.S3Exception; import java.util.ArrayList; import java.util.List; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * <p> * For more information, see the following documentation topic: * <p> * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class LifecycleConfiguration { public static void main(String[] args) { final String usage = """ Usage: <bucketName> <accountId>\s Where: bucketName - The Amazon Simple Storage Service (Amazon S3) bucket to upload an object into. accountId - The id of the account that owns the Amazon S3 bucket. """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String bucketName = args[0]; String accountId = args[1]; Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() .region(region) .build(); setLifecycleConfig(s3, bucketName, accountId); getLifecycleConfig(s3, bucketName, accountId); deleteLifecycleConfig(s3, bucketName, accountId); System.out.println("You have successfully created, updated, and deleted a Lifecycle configuration"); s3.close(); } /** * Sets the lifecycle configuration for an Amazon S3 bucket. * * @param s3 The Amazon S3 client to use for the operation. * @param bucketName The name of the Amazon S3 bucket. * @param accountId The expected owner of the Amazon S3 bucket. * * @throws S3Exception if there is an error setting the lifecycle configuration. */ public static void setLifecycleConfig(S3Client s3, String bucketName, String accountId) { try { // Create a rule to archive objects with the "glacierobjects/" prefix to Amazon // S3 Glacier. LifecycleRuleFilter ruleFilter = LifecycleRuleFilter.builder() .prefix("glacierobjects/") .build(); Transition transition = Transition.builder() .storageClass(TransitionStorageClass.GLACIER) .days(0) .build(); LifecycleRule rule1 = LifecycleRule.builder() .id("Archive immediately rule") .filter(ruleFilter) .transitions(transition) .status(ExpirationStatus.ENABLED) .build(); // Create a second rule. Transition transition2 = Transition.builder() .storageClass(TransitionStorageClass.GLACIER) .days(0) .build(); List<Transition> transitionList = new ArrayList<>(); transitionList.add(transition2); LifecycleRuleFilter ruleFilter2 = LifecycleRuleFilter.builder() .prefix("glacierobjects/") .build(); LifecycleRule rule2 = LifecycleRule.builder() .id("Archive and then delete rule") .filter(ruleFilter2) .transitions(transitionList) .status(ExpirationStatus.ENABLED) .build(); // Add the LifecycleRule objects to an ArrayList. ArrayList<LifecycleRule> ruleList = new ArrayList<>(); ruleList.add(rule1); ruleList.add(rule2); BucketLifecycleConfiguration lifecycleConfiguration = BucketLifecycleConfiguration.builder() .rules(ruleList) .build(); PutBucketLifecycleConfigurationRequest putBucketLifecycleConfigurationRequest = PutBucketLifecycleConfigurationRequest .builder() .bucket(bucketName) .lifecycleConfiguration(lifecycleConfiguration) .expectedBucketOwner(accountId) .build(); s3.putBucketLifecycleConfiguration(putBucketLifecycleConfigurationRequest); } catch (S3Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } /** * Retrieves the lifecycle configuration for an Amazon S3 bucket and adds a new lifecycle rule to it. * * @param s3 the S3Client instance used to interact with Amazon S3 * @param bucketName the name of the Amazon S3 bucket * @param accountId the expected owner of the Amazon S3 bucket */ public static void getLifecycleConfig(S3Client s3, String bucketName, String accountId) { try { GetBucketLifecycleConfigurationRequest getBucketLifecycleConfigurationRequest = GetBucketLifecycleConfigurationRequest .builder() .bucket(bucketName) .expectedBucketOwner(accountId) .build(); GetBucketLifecycleConfigurationResponse response = s3 .getBucketLifecycleConfiguration(getBucketLifecycleConfigurationRequest); List<LifecycleRule> newList = new ArrayList<>(); List<LifecycleRule> rules = response.rules(); for (LifecycleRule rule : rules) { newList.add(rule); } // Add a new rule with both a prefix predicate and a tag predicate. LifecycleRuleFilter ruleFilter = LifecycleRuleFilter.builder() .prefix("YearlyDocuments/") .build(); Transition transition = Transition.builder() .storageClass(TransitionStorageClass.GLACIER) .days(3650) .build(); LifecycleRule rule1 = LifecycleRule.builder() .id("NewRule") .filter(ruleFilter) .transitions(transition) .status(ExpirationStatus.ENABLED) .build(); // Add the new rule to the list. newList.add(rule1); BucketLifecycleConfiguration lifecycleConfiguration = BucketLifecycleConfiguration.builder() .rules(newList) .build(); PutBucketLifecycleConfigurationRequest putBucketLifecycleConfigurationRequest = PutBucketLifecycleConfigurationRequest .builder() .bucket(bucketName) .lifecycleConfiguration(lifecycleConfiguration) .expectedBucketOwner(accountId) .build(); s3.putBucketLifecycleConfiguration(putBucketLifecycleConfigurationRequest); } catch (S3Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } /** * Deletes the lifecycle configuration for an Amazon S3 bucket. * * @param s3 the {@link S3Client} to use for the operation * @param bucketName the name of the S3 bucket * @param accountId the expected account owner of the S3 bucket * * @throws S3Exception if an error occurs while deleting the lifecycle configuration */ public static void deleteLifecycleConfig(S3Client s3, String bucketName, String accountId) { try { DeleteBucketLifecycleRequest deleteBucketLifecycleRequest = DeleteBucketLifecycleRequest .builder() .bucket(bucketName) .expectedBucketOwner(accountId) .build(); s3.deleteBucketLifecycle(deleteBucketLifecycleRequest); } catch (S3Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
Python
SDK Python용(Boto3)
참고

에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

class BucketWrapper: """Encapsulates S3 bucket actions.""" def __init__(self, bucket): """ :param bucket: A Boto3 Bucket resource. This is a high-level resource in Boto3 that wraps bucket actions in a class-like structure. """ self.bucket = bucket self.name = bucket.name def put_lifecycle_configuration(self, lifecycle_rules): """ Apply a lifecycle configuration to the bucket. The lifecycle configuration can be used to archive or delete the objects in the bucket according to specified parameters, such as a number of days. :param lifecycle_rules: The lifecycle rules to apply. """ try: self.bucket.LifecycleConfiguration().put( LifecycleConfiguration={"Rules": lifecycle_rules} ) logger.info( "Put lifecycle rules %s for bucket '%s'.", lifecycle_rules, self.bucket.name, ) except ClientError: logger.exception( "Couldn't put lifecycle rules for bucket '%s'.", self.bucket.name ) raise