Enable Object Versioning
This will help you store different versions of an object.
Components
- Credentials
- Bucket Name
- .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 EnableBucketVersioning
{
class EnableBucketVersioning
{
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>" };
_s3Client = new AmazonS3Client(awsCredentials, config);
EnableBucketVersioningAsync().Wait();
}
private static async Task EnableBucketVersioningAsync()
{
try
{
PutBucketVersioningResponse response = await _s3Client.PutBucketVersioningAsync(new PutBucketVersioningRequest
{
BucketName = bucketName,
VersioningConfig = new S3BucketVersioningConfig() { Status = VersionStatus.Enabled }
});
Console.WriteLine($"Versioning enabled in {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 = $config['sample_bucket'];
try {
$result = $client->getBucketCors([
'Bucket' => $bucket, // REQUIRED
]);
var_dump($result);
} catch (AwsException $e) {
// Display error message
echo $e->getMessage();
echo "\n";
}
import boto3
import logging
from botocore.exceptions import ClientError
# Configure logging
logging.basicConfig(level=logging.INFO)
try:
# S3 resource
s3_resource = boto3.resource(
'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:
bucket_name = 'sample_bucket_name'
bucket_versioning = s3_resource.Bucket(bucket_name).Versioning()
bucket_versioning.enable()
logging.info(bucket_versioning.status)
except ClientError as e:
logging.error(e)
// Import required AWS SDK clients and commands for Node.js
const {
S3Client,
GetBucketVersioningCommand,
PutBucketVersioningCommand,
} = 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 = 'sample_bucket';
const run = async () => {
try {
const response = await s3.send(
new GetBucketVersioningCommand({
Bucket: BUCKET_NAME,
})
);
console.log('Success', response);
const response2 = await s3.send(
new PutBucketVersioningCommand({
Bucket: BUCKET_NAME,
VersioningConfiguration: {
Status: 'Enabled',
},
})
);
console.log('Success', response2);
} catch (err) {
console.log('Error', err);
}
};
run();
package main
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"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"
)
// Enables Versioning on bucket
//
// Usage:
// go run s3_enable_bucket_versioning.go BUCKET
func main() {
if len(os.Args) != 2 {
exitErrorf("Bucket name required\nUsage: go run", os.Args[0], "BUCKET")
}
bucket := os.Args[1]
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>"),
})
input := &s3.PutBucketVersioningInput{
Bucket: aws.String(bucket),
VersioningConfiguration: &s3.VersioningConfiguration{
MFADelete: aws.String("Disabled"),
Status: aws.String("Enabled"),
},
}
result, err := svc.PutBucketVersioning(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
fmt.Println("Versioning enabled 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_enable_bucket_versioning.go:
go run s3_enable_bucket_versioning.go BUCKET