PutBucketLifecycleConfiguration 搭配 AWS SDK或 使用 CLI - AWS SDK 程式碼範例

文件範例儲存庫中有更多 AWS SDK可用的範例。 AWS SDK GitHub

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

PutBucketLifecycleConfiguration 搭配 AWS 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

檔案lifecycle.json是目前資料夾中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 for 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