Configure Bucket Lifecycle Policies
Components
- Credentials
- Bucket Name
- Lifecycle Policies
- .NET
- PHP
- Python
- Javascript
- GO
using Amazon;
using Amazon.S3;
using Amazon.S3.Model;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace PutBucketLifecycleConfiguration
{
class PutBucketLifecycleConfiguration
{
private const string bucketName = "<BUCKET_NAME>";
private static IAmazonS3 _s3Client;
public static void Main()
{
var awsCredentials = new Amazon.Runtime.BasicAWSCredentials("<ACCESS_KEY>", "<SECRET_KEY>");
var config = new AmazonS3Config { ServiceURL = "<ENDPOINT_URL>" };
_s3Client = new AmazonS3Client(awsCredentials, config);
PutBucketLifecycle().Wait();
}
private static async Task PutBucketLifecycle()
{
try
{
var lifecycleConfiguration = new LifecycleConfiguration
{
Rules = new List<LifecycleRule>
{
new LifecycleRule
{
Filter = new LifecycleFilter
{
LifecycleFilterPredicate = new LifecyclePrefixPredicate
{
Prefix = "someprefix/"
}
},
Expiration = new LifecycleRuleExpiration { Days = 10 },
Status = "Enabled",
}
}
};
var putLifecycleConfigurationRequest = new PutLifecycleConfigurationRequest
{
BucketName = bucketName,
Configuration = lifecycleConfiguration
};
await _s3Client.PutLifecycleConfigurationAsync(putLifecycleConfigurationRequest);
Console.WriteLine($"Lifecycle configuration added to {bucketName} bucket");
}
catch (AmazonS3Exception amazonS3Exception)
{
Console.WriteLine("An AmazonS3Exception was thrown. Exception: " + amazonS3Exception.ToString());
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.ToString());
}
}
}
}
<?php
require('client.php');
$bucket = '<BUCKET_NAME>';
$params = [
'Bucket' => $bucket,
'LifecycleConfiguration' => [
'Rules' => [
[
'Expiration' => [
'Days' => 10,
],
'Status' => 'Enabled',
'Prefix' => ''
],
],
],
];
try {
$resp = $client->putBucketLifecycle($params);
var_dump($resp);
} catch (AwsException $e) {
// Display error message
echo $e->getMessage();
echo "\n";
}
import boto3
import logging
from datetime import datetime
from botocore.exceptions import ClientError
logging.basicConfig(level=logging.INFO)
try:
s3_client = boto3.client(
's3',
endpoint_url='<ENDPOINT_URL>',
aws_access_key_id='<ACCESS_KEY>',
aws_secret_access_key='<SECRET_KEY>'
)
except Exception as exc:
logging.error(exc)
else:
try:
response = s3_client.put_bucket_lifecycle_configuration(
Bucket='<BUCKET_NAME>',
LifecycleConfiguration={
'Rules': [
{
'Expiration': {
'Days': 10,
},
'Prefix': 'downloads',
'Status': 'Enabled',
},
]
},
)
logging.info(response)
except ClientError as exc:
logging.error(exc)
// Import required AWS SDK clients and commands for Node.js
const {
S3Client,
PutBucketLifecycleConfigurationCommand,
} = require('@aws-sdk/client-s3');
// Create an S3 client service object
const s3 = new S3Client({
region: 'default',
endpoint: '<ENDPOINT_URL>',
credentials: {
accessKeyId: '<ACCESS_KEY>',
secretAccessKey: '<SECRET_KEY>',
},
});
const BUCKET_NAME = '<BUCKET_NAME>';
const run = async () => {
try {
const params = {
Bucket: BUCKET_NAME,
LifecycleConfiguration: {
Rules: [
{
Expiration: {
Days: 10,
},
Prefix: '',
Status: 'Enabled',
},
],
},
};
const response = await s3.send(
new PutBucketLifecycleConfigurationCommand(params)
);
console.log('Success', response);
} catch (err) {
console.log('Error', err);
}
};
run();
package main
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"fmt"
"os"
)
// Puts bucket lifecycle configuration
//
// Usage:
// go run s3_put_bucket_lifecycle_configuration.go BUCKET
func main() {
if len(os.Args) < 2 {
exitErrorf("Bucket name: go run", os.Args[0], "BUCKET")
}
bucket := os.Args[1]
// Initialize a session in us-west-2 that the SDK will use to load
// credentials from the shared credentials file ~/.aws/credentials.
sess, err := session.NewSession(&aws.Config{
Credentials: credentials.NewStaticCredentials("<ACCESS_KEY>", "<SECRET_KEY>", ""),
})
svc := s3.New(sess, &aws.Config{
Region: aws.String("default"),
Endpoint: aws.String("<ENDPOINT_URL>"),
})
params := &s3.PutBucketLifecycleConfigurationInput{
Bucket: &bucket,
LifecycleConfiguration: &s3.BucketLifecycleConfiguration{
Rules: []*s3.LifecycleRule{
{
Expiration: &s3.LifecycleExpiration{
Days: aws.Int64(10),
},
Filter: &s3.LifecycleRuleFilter{
Prefix: aws.String("documents/"),
},
Status: aws.String("Enabled"),
},
},
},
}
// Set bucket Lifecycle configuration
_, err = svc.PutBucketLifecycleConfiguration(params)
if err != nil {
exitErrorf(err.Error())
}
fmt.Println("Congratulations. You put lifecycle configuration on bucket", bucket)
}
func exitErrorf(msg string, args ...interface{}) {
fmt.Fprintf(os.Stderr, msg+"\n", args...)
os.Exit(1)
}
The following command can be used to execute the aforementioned code, presuming the code file is called s3_put_bucket_lifecycle_configuration.go:
go run s3_put_bucket_lifecycle_configuration.go BUCKET