Verwendung PutBucketLifecycleConfiguration mit einem AWS SDK oder CLI - Amazon Simple Storage Service

Die vorliegende Übersetzung wurde maschinell erstellt. Im Falle eines Konflikts oder eines Widerspruchs zwischen dieser übersetzten Fassung und der englischen Fassung (einschließlich infolge von Verzögerungen bei der Übersetzung) ist die englische Fassung maßgeblich.

Verwendung PutBucketLifecycleConfiguration mit einem AWS SDK oder CLI

Die folgenden Codebeispiele zeigen, wie es verwendet wirdPutBucketLifecycleConfiguration.

Aktionsbeispiele sind Codeauszüge aus größeren Programmen und müssen im Kontext ausgeführt werden. Sie können diese Aktion in den folgenden Codebeispielen im Kontext sehen:

.NET
AWS SDK for .NET
Anmerkung

Es gibt noch mehr dazu GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

/// <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

Der folgende Befehl wendet eine Lebenszykluskonfiguration auf einen Bucket mit dem Namen anmy-bucket:

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

Die Datei lifecycle.json ist ein JSON-Dokument im aktuellen Ordner, das zwei Regeln festlegt:

{ "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" } ] }

Die erste Regel verschiebt Dateien mit dem Präfix am angegebenen Datum rotated nach Glacier. Die zweite Regel verschiebt alte Objektversionen nach Glacier, wenn sie nicht mehr aktuell sind. Informationen zu akzeptablen Zeitstempelformaten finden Sie unter Parameterwerte angeben im AWS CLI-Benutzerhandbuch.

Java
SDK für Java 2.x
Anmerkung

Es gibt noch mehr dazu GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

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. * * For more information, see the following documentation topic: * * 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(); } 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); } } // Retrieve the configuration and add a new rule. 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); } } // Delete the configuration from the Amazon S3 bucket. 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 für Python (Boto3)
Anmerkung

Es gibt noch mehr dazu GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

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

Eine vollständige Liste der AWS SDK-Entwicklerhandbücher und Codebeispiele finden Sie unter. Verwenden Sie diesen Dienst mit einem SDK AWS Dieses Thema enthält auch Informationen zu den ersten Schritten und Details zu früheren SDK-Versionen.