Amazon S3 Construct Library
Define an S3 bucket.
const bucket = new s3.Bucket(this, 'MyFirstBucket');
bucket = s3.Bucket(self, "MyFirstBucket")
Bucket bucket = new Bucket(this, "MyFirstBucket");
var bucket = new Bucket(this, "MyFirstBucket");
bucket := s3.NewBucket(this, jsii.String("MyFirstBucket"))
Bucket constructs expose the following deploy-time attributes:
bucketArn- the ARN of the bucket (i.e.arn:aws:s3:::amzn-s3-demo-bucket)bucketName- the name of the bucket (i.e.amzn-s3-demo-bucket)bucketWebsiteUrl- the Website URL of the bucket (i.e.http://amzn-s3-demo-bucket.s3-website-us-west-1.amazonaws.com)bucketDomainName- the URL of the bucket (i.e.amzn-s3-demo-bucket.s3.amazonaws.com)bucketDualStackDomainName- the dual-stack URL of the bucket (i.e.amzn-s3-demo-bucket.s3.dualstack.eu-west-1.amazonaws.com)bucketRegionalDomainName- the regional URL of the bucket (i.e.amzn-s3-demo-bucket.s3.eu-west-1.amazonaws.com)arnForObjects(pattern)- the ARN of an object or objects within the bucket (i.e.arn:aws:s3:::amzn-s3-demo-bucket/exampleobject.pngorarn:aws:s3:::amzn-s3-demo-bucket/Development/*)urlForObject(key)- the HTTP URL of an object within the bucket (i.e.https://s3---cn-north-1.amazonaws.com.rproxy.goskope.com.cn/china-bucket/mykey)virtualHostedUrlForObject(key)- the virtual-hosted style HTTP URL of an object within the bucket (i.e.https://china-bucket-s3---cn-north-1.amazonaws.com.rproxy.goskope.com.cn/mykey)s3UrlForObject(key)- the S3 URL of an object within the bucket (i.e.s3://bucket/mykey)
Encryption
Define a KMS-encrypted bucket:
const bucket = new s3.Bucket(this, 'MyEncryptedBucket', {
encryption: s3.BucketEncryption.KMS,
});
// you can access the encryption key:
assert(bucket.encryptionKey instanceof kms.Key);
bucket = s3.Bucket(self, "MyEncryptedBucket",
encryption=s3.BucketEncryption.KMS
)
# you can access the encryption key:
assert(bucket.encryption_key instanceof kms.Key)
Bucket bucket = Bucket.Builder.create(this, "MyEncryptedBucket")
.encryption(BucketEncryption.KMS)
.build();
// you can access the encryption key:
assert(bucket.getEncryptionKey() instanceof Key);
var bucket = new Bucket(this, "MyEncryptedBucket", new BucketProps {
Encryption = BucketEncryption.KMS
});
// you can access the encryption key:
Assert(bucket.EncryptionKey instanceof Key);
bucket := s3.NewBucket(this, jsii.String("MyEncryptedBucket"), &BucketProps{
Encryption: s3.BucketEncryption_KMS,
})
// you can access the encryption key:
assert(bucket.EncryptionKey instanceof kms.Key)
You can also supply your own key:
const myKmsKey = new kms.Key(this, 'MyKey');
const bucket = new s3.Bucket(this, 'MyEncryptedBucket', {
encryption: s3.BucketEncryption.KMS,
encryptionKey: myKmsKey,
});
assert(bucket.encryptionKey === myKmsKey);
my_kms_key = kms.Key(self, "MyKey")
bucket = s3.Bucket(self, "MyEncryptedBucket",
encryption=s3.BucketEncryption.KMS,
encryption_key=my_kms_key
)
assert(bucket.encryption_key == my_kms_key)
Key myKmsKey = new Key(this, "MyKey");
Bucket bucket = Bucket.Builder.create(this, "MyEncryptedBucket")
.encryption(BucketEncryption.KMS)
.encryptionKey(myKmsKey)
.build();
assert(bucket.getEncryptionKey() == myKmsKey);
var myKmsKey = new Key(this, "MyKey");
var bucket = new Bucket(this, "MyEncryptedBucket", new BucketProps {
Encryption = BucketEncryption.KMS,
EncryptionKey = myKmsKey
});
Assert(bucket.EncryptionKey == myKmsKey);
myKmsKey := kms.NewKey(this, jsii.String("MyKey"))
bucket := s3.NewBucket(this, jsii.String("MyEncryptedBucket"), &BucketProps{
Encryption: s3.BucketEncryption_KMS,
EncryptionKey: myKmsKey,
})
assert(bucket.EncryptionKey == myKmsKey)
Enable KMS-SSE encryption via S3 Bucket Keys:
const bucket = new s3.Bucket(this, 'MyEncryptedBucket', {
encryption: s3.BucketEncryption.KMS,
bucketKeyEnabled: true,
});
bucket = s3.Bucket(self, "MyEncryptedBucket",
encryption=s3.BucketEncryption.KMS,
bucket_key_enabled=True
)
Bucket bucket = Bucket.Builder.create(this, "MyEncryptedBucket")
.encryption(BucketEncryption.KMS)
.bucketKeyEnabled(true)
.build();
var bucket = new Bucket(this, "MyEncryptedBucket", new BucketProps {
Encryption = BucketEncryption.KMS,
BucketKeyEnabled = true
});
bucket := s3.NewBucket(this, jsii.String("MyEncryptedBucket"), &BucketProps{
Encryption: s3.BucketEncryption_KMS,
BucketKeyEnabled: jsii.Boolean(true),
})
Use BucketEncryption.ManagedKms to use the S3 master KMS key:
const bucket = new s3.Bucket(this, 'Buck', {
encryption: s3.BucketEncryption.KMS_MANAGED,
});
assert(bucket.encryptionKey == null);
bucket = s3.Bucket(self, "Buck",
encryption=s3.BucketEncryption.KMS_MANAGED
)
assert(bucket.encryption_key == null)
Bucket bucket = Bucket.Builder.create(this, "Buck")
.encryption(BucketEncryption.KMS_MANAGED)
.build();
assert(bucket.getEncryptionKey() == null);
var bucket = new Bucket(this, "Buck", new BucketProps {
Encryption = BucketEncryption.KMS_MANAGED
});
Assert(bucket.EncryptionKey == null);
bucket := s3.NewBucket(this, jsii.String("Buck"), &BucketProps{
Encryption: s3.BucketEncryption_KMS_MANAGED,
})
assert(bucket.EncryptionKey == nil)
Enable DSSE encryption:
const bucket = new s3.Bucket(stack, 'MyDSSEBucket', {
encryption: s3.BucketEncryption.DSSE_MANAGED,
bucketKeyEnabled: true,
});
Explicitly block uploads encrypted with SSE-C:
const bucket = new s3.Bucket(this, 'MySsecBlockedBucket', {
blockedEncryptionTypes: [s3.BlockedEncryptionType.SSE_C],
});
bucket = s3.Bucket(self, "MySsecBlockedBucket",
blocked_encryption_types=[s3.BlockedEncryptionType.SSE_C]
)
Bucket bucket = Bucket.Builder.create(this, "MySsecBlockedBucket")
.blockedEncryptionTypes(List.of(BlockedEncryptionType.SSE_C))
.build();
var bucket = new Bucket(this, "MySsecBlockedBucket", new BucketProps {
BlockedEncryptionTypes = new [] { BlockedEncryptionType.SSE_C }
});
bucket := s3.NewBucket(this, jsii.String("MySsecBlockedBucket"), &BucketProps{
BlockedEncryptionTypes: []BlockedEncryptionType{
s3.BlockedEncryptionType_SSE_C(),
},
})
Allow uploads with all encryption types:
const bucket = new s3.Bucket(this, 'MyBucket', {
blockedEncryptionTypes: [s3.BlockedEncryptionType.NONE],
});
bucket = s3.Bucket(self, "MyBucket",
blocked_encryption_types=[s3.BlockedEncryptionType.NONE]
)
Bucket bucket = Bucket.Builder.create(this, "MyBucket")
.blockedEncryptionTypes(List.of(BlockedEncryptionType.NONE))
.build();
var bucket = new Bucket(this, "MyBucket", new BucketProps {
BlockedEncryptionTypes = new [] { BlockedEncryptionType.NONE }
});
bucket := s3.NewBucket(this, jsii.String("MyBucket"), &BucketProps{
BlockedEncryptionTypes: []BlockedEncryptionType{
s3.BlockedEncryptionType_NONE(),
},
})
Permissions
A bucket policy will be automatically created for the bucket upon the first call to addToResourcePolicy(statement):
const bucket = new s3.Bucket(this, 'MyBucket');
const result = bucket.addToResourcePolicy(
new iam.PolicyStatement({
actions: ['s3:GetObject'],
resources: [bucket.arnForObjects('file.txt')],
principals: [new iam.AccountRootPrincipal()],
})
);
bucket = s3.Bucket(self, "MyBucket")
result = bucket.add_to_resource_policy(
iam.PolicyStatement(
actions=["s3:GetObject"],
resources=[bucket.arn_for_objects("file.txt")],
principals=[iam.AccountRootPrincipal()]
))
Bucket bucket = new Bucket(this, "MyBucket");
AddToResourcePolicyResult result = bucket.addToResourcePolicy(
PolicyStatement.Builder.create()
.actions(List.of("s3:GetObject"))
.resources(List.of(bucket.arnForObjects("file.txt")))
.principals(List.of(new AccountRootPrincipal()))
.build());
var bucket = new Bucket(this, "MyBucket");
var result = bucket.AddToResourcePolicy(
new PolicyStatement(new PolicyStatementProps {
Actions = new [] { "s3:GetObject" },
Resources = new [] { bucket.ArnForObjects("file.txt") },
Principals = new [] { new AccountRootPrincipal() }
}));
bucket := s3.NewBucket(this, jsii.String("MyBucket"))
result := bucket.AddToResourcePolicy(
iam.NewPolicyStatement(&PolicyStatementProps{
Actions: []*string{
jsii.String("s3:GetObject"),
},
Resources: []*string{
bucket.ArnForObjects(jsii.String("file.txt")),
},
Principals: []IPrincipal{
iam.NewAccountRootPrincipal(),
},
}))
If you try to add a policy statement to an existing bucket, this method will not do anything:
const bucket = s3.Bucket.fromBucketName(this, 'existingBucket', 'amzn-s3-demo-bucket');
// No policy statement will be added to the resource
const result = bucket.addToResourcePolicy(
new iam.PolicyStatement({
actions: ['s3:GetObject'],
resources: [bucket.arnForObjects('file.txt')],
principals: [new iam.AccountRootPrincipal()],
})
);
bucket = s3.Bucket.from_bucket_name(self, "existingBucket", "amzn-s3-demo-bucket")
# No policy statement will be added to the resource
result = bucket.add_to_resource_policy(
iam.PolicyStatement(
actions=["s3:GetObject"],
resources=[bucket.arn_for_objects("file.txt")],
principals=[iam.AccountRootPrincipal()]
))
IBucket bucket = Bucket.fromBucketName(this, "existingBucket", "amzn-s3-demo-bucket");
// No policy statement will be added to the resource
AddToResourcePolicyResult result = bucket.addToResourcePolicy(
PolicyStatement.Builder.create()
.actions(List.of("s3:GetObject"))
.resources(List.of(bucket.arnForObjects("file.txt")))
.principals(List.of(new AccountRootPrincipal()))
.build());
var bucket = Bucket.FromBucketName(this, "existingBucket", "amzn-s3-demo-bucket");
// No policy statement will be added to the resource
var result = bucket.AddToResourcePolicy(
new PolicyStatement(new PolicyStatementProps {
Actions = new [] { "s3:GetObject" },
Resources = new [] { bucket.ArnForObjects("file.txt") },
Principals = new [] { new AccountRootPrincipal() }
}));
bucket := s3.Bucket_FromBucketName(this, jsii.String("existingBucket"), jsii.String("amzn-s3-demo-bucket"))
// No policy statement will be added to the resource
result := bucket.AddToResourcePolicy(
iam.NewPolicyStatement(&PolicyStatementProps{
Actions: []*string{
jsii.String("s3:GetObject"),
},
Resources: []*string{
bucket.ArnForObjects(jsii.String("file.txt")),
},
Principals: []IPrincipal{
iam.NewAccountRootPrincipal(),
},
}))
That's because it's not possible to tell whether the bucket already has a policy attached, let alone to re-use that policy to add more statements to it. We recommend that you always check the result of the call:
const bucket = new s3.Bucket(this, 'MyBucket');
const result = bucket.addToResourcePolicy(
new iam.PolicyStatement({
actions: ['s3:GetObject'],
resources: [bucket.arnForObjects('file.txt')],
principals: [new iam.AccountRootPrincipal()],
})
);
if (!result.statementAdded) {
// Uh-oh! Someone probably made a mistake here.
}
bucket = s3.Bucket(self, "MyBucket")
result = bucket.add_to_resource_policy(
iam.PolicyStatement(
actions=["s3:GetObject"],
resources=[bucket.arn_for_objects("file.txt")],
principals=[iam.AccountRootPrincipal()]
))
if not result.statement_added:
pass
Bucket bucket = new Bucket(this, "MyBucket");
AddToResourcePolicyResult result = bucket.addToResourcePolicy(
PolicyStatement.Builder.create()
.actions(List.of("s3:GetObject"))
.resources(List.of(bucket.arnForObjects("file.txt")))
.principals(List.of(new AccountRootPrincipal()))
.build());
if (!result.getStatementAdded()) {
}
var bucket = new Bucket(this, "MyBucket");
var result = bucket.AddToResourcePolicy(
new PolicyStatement(new PolicyStatementProps {
Actions = new [] { "s3:GetObject" },
Resources = new [] { bucket.ArnForObjects("file.txt") },
Principals = new [] { new AccountRootPrincipal() }
}));
if (!result.StatementAdded)
{
}
bucket := s3.NewBucket(this, jsii.String("MyBucket"))
result := bucket.AddToResourcePolicy(
iam.NewPolicyStatement(&PolicyStatementProps{
Actions: []*string{
jsii.String("s3:GetObject"),
},
Resources: []*string{
bucket.ArnForObjects(jsii.String("file.txt")),
},
Principals: []IPrincipal{
iam.NewAccountRootPrincipal(),
},
}))
if !result.StatementAdded {}
The bucket policy can be directly accessed after creation to add statements or adjust the removal policy.
const bucket = new s3.Bucket(this, 'MyBucket');
bucket.policy?.applyRemovalPolicy(cdk.RemovalPolicy.RETAIN);
bucket = s3.Bucket(self, "MyBucket")
bucket.policy.apply_removal_policy(cdk.RemovalPolicy.RETAIN)
Bucket bucket = new Bucket(this, "MyBucket");
bucket.policy.applyRemovalPolicy(RemovalPolicy.RETAIN);
var bucket = new Bucket(this, "MyBucket");
bucket.Policy.ApplyRemovalPolicy(RemovalPolicy.RETAIN);
bucket := s3.NewBucket(this, jsii.String("MyBucket"))
bucket.Policy.ApplyRemovalPolicy(cdk.RemovalPolicy_RETAIN)
Most of the time, you won't have to manipulate the bucket policy directly. Instead, buckets have "grant" methods called to give prepackaged sets of permissions to other resources. For example:
declare const myLambda: lambda.Function;
const bucket = new s3.Bucket(this, 'MyBucket');
bucket.grantReadWrite(myLambda);
# my_lambda: lambda.Function
bucket = s3.Bucket(self, "MyBucket")
bucket.grant_read_write(my_lambda)
Function myLambda;
Bucket bucket = new Bucket(this, "MyBucket");
bucket.grantReadWrite(myLambda);
Function myLambda;
var bucket = new Bucket(this, "MyBucket");
bucket.GrantReadWrite(myLambda);
var myLambda Function
bucket := s3.NewBucket(this, jsii.String("MyBucket"))
bucket.GrantReadWrite(myLambda)
Will give the Lambda's execution role permissions to read and write from the bucket.
Understanding "grant" Methods
The S3 construct library provides several grant methods for IBucketRef instances, which can be accessed via the BucketGrants class:
declare const principal: iam.IPrincipal;
declare const bucket: s3.IBucketRef;
s3.BucketGrants.fromBucket(bucket).delete(principal);
# principal: iam.IPrincipal
# bucket: s3.IBucketRef
s3.BucketGrants.from_bucket(bucket).delete(principal)
IPrincipal principal;
IBucketRef bucket;
BucketGrants.fromBucket(bucket).delete(principal);
IPrincipal principal;
IBucketRef bucket;
BucketGrants.FromBucket(bucket).Delete(principal);
var principal IPrincipal
var bucket IBucketRef
s3.BucketGrants_FromBucket(bucket).Delete(principal)
If bucket is an instance of CfnBucket, and the grants process involves adding statements to the bucket policy, then the BucketGrants class will, by default, do the same thing it would do for an instance of Bucket: create a new bucket policy (or reuse an existing one) and add the necessary statements to it.
But if you want to customize this behavior, you can register an instance of IResourcePolicyFactory for the AWS::S3::Bucket CloudFormation type:
import { CfnResource } from 'aws-cdk-lib';
import { AddToResourcePolicyResult, IResourcePolicyFactory, IResourceWithPolicyV2, PolicyStatement, ResourceWithPolicies } from 'aws-cdk-lib/aws-iam';
import { ResourceEnvironment } from 'aws-cdk-lib/interfaces';
import { Construct } from 'constructs';
declare const scope: Construct;
class MyResourceWithPolicy implements IResourceWithPolicyV2 {
public readonly env: ResourceEnvironment;
private readonly resource: CfnResource;
constructor(resource: CfnResource) {
this.resource = resource;
this.env = resource.env;
}
public addToResourcePolicy(statement: PolicyStatement): AddToResourcePolicyResult {
// custom implementation to add the statement to the resource policy
return { statementAdded: true, policyDependable: this.resource };
}
}
class MyFactory implements IResourcePolicyFactory {
public forResource(resource: CfnResource): IResourceWithPolicyV2 {
return new MyResourceWithPolicy(resource);
}
}
ResourceWithPolicies.register(scope, 'AWS::S3::Bucket', new MyFactory());
from aws_cdk.aws_iam import AddToResourcePolicyResult
from aws_cdk import CfnResource
from aws_cdk.aws_iam import AddToResourcePolicyResult, IResourcePolicyFactory, IResourceWithPolicyV2, PolicyStatement, ResourceWithPolicies
from aws_cdk.interfaces import ResourceEnvironment
from constructs import Construct
# scope: Construct
@jsii.implements(IResourceWithPolicyV2)
class MyResourceWithPolicy:
def __init__(self, resource):
self.resource = resource
self.env = resource.env
def add_to_resource_policy(self, statement):
# custom implementation to add the statement to the resource policy
return AddToResourcePolicyResult(statement_added=True, policy_dependable=self.resource)
@jsii.implements(IResourcePolicyFactory)
class MyFactory:
def for_resource(self, resource):
return MyResourceWithPolicy(resource)
ResourceWithPolicies.register(scope, "AWS::S3::Bucket", MyFactory())
import software.amazon.awscdk.CfnResource;
import software.amazon.awscdk.services.iam.AddToResourcePolicyResult;
import software.amazon.awscdk.services.iam.IResourcePolicyFactory;
import software.amazon.awscdk.services.iam.IResourceWithPolicyV2;
import software.amazon.awscdk.services.iam.PolicyStatement;
import software.amazon.awscdk.services.iam.ResourceWithPolicies;
import software.amazon.awscdk.interfaces.ResourceEnvironment;
import software.constructs.Construct;
Construct scope;
public class MyResourceWithPolicy implements IResourceWithPolicyV2 {
public final ResourceEnvironment env;
private final CfnResource resource;
public MyResourceWithPolicy(CfnResource resource) {
this.resource = resource;
this.env = resource.getEnv();
}
public AddToResourcePolicyResult addToResourcePolicy(PolicyStatement statement) {
// custom implementation to add the statement to the resource policy
return AddToResourcePolicyResult.builder().statementAdded(true).policyDependable(this.resource).build();
}
}
public class MyFactory implements IResourcePolicyFactory {
public IResourceWithPolicyV2 forResource(CfnResource resource) {
return new MyResourceWithPolicy(resource);
}
}
ResourceWithPolicies.register(scope, "AWS::S3::Bucket", new MyFactory());
using Amazon.CDK;
using Amazon.CDK.AWS.IAM;
using Amazon.CDK.Interfaces;
using Constructs;
Construct scope;
class MyResourceWithPolicy : IResourceWithPolicyV2
{
public ResourceEnvironment Env { get; }
private readonly CfnResource resource;
public MyResourceWithPolicy(CfnResource resource)
{
resource = resource;
Env = resource.Env;
}
public AddToResourcePolicyResult AddToResourcePolicy(PolicyStatement statement)
{
// custom implementation to add the statement to the resource policy
return new AddToResourcePolicyResult { StatementAdded = true, PolicyDependable = resource };
}
}
class MyFactory : IResourcePolicyFactory
{
public IResourceWithPolicyV2 ForResource(CfnResource resource)
{
return new MyResourceWithPolicy(resource);
}
}
ResourceWithPolicies.Register(scope, "AWS::S3::Bucket", new MyFactory());
import "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/constructs-go/constructs"
var scope Construct
type myResourceWithPolicy struct {
env ResourceEnvironment
resource CfnResource
}
func newMyResourceWithPolicy(resource CfnResource) *myResourceWithPolicy {
this := &myResourceWithPolicy{}
this.resource = resource
this.env = resource.env
return this
}
func (this *myResourceWithPolicy) addToResourcePolicy(statement PolicyStatement) AddToResourcePolicyResult {
// custom implementation to add the statement to the resource policy
return &AddToResourcePolicyResult{
StatementAdded: jsii.Boolean(true),
PolicyDependable: this.resource,
}
}
type myFactory struct {
}
func (this *myFactory) forResource(resource CfnResource) IResourceWithPolicyV2 {
return NewMyResourceWithPolicy(*resource)
}
awscdk.ResourceWithPolicies_Register(scope, jsii.String("AWS::S3::Bucket"), NewMyFactory())
IResourcePolicyFactory is responsible for converting a construct into a IResourceWithPolicyV2, effectively providing an ad-hoc way to extend the behavior of L1s to support grants the same way as L2s do.
The BucketGrants class has many methods, but two of them have a special behavior. These two accept an objectsKeyPattern parameter to restrict granted permissions to specific resources:
readreadWrite
When examining the synthesized policy, you'll notice it includes both your specified object key patterns and the bucket itself. This is by design. Some permissions (like s3:ListBucket) apply at the bucket level, while others (like s3:GetObject) apply to specific objects.
Specifically, the s3:ListBucket action operates on bucket resources and requires the bucket ARN to work properly. This might be seen as a bug, giving the impression that more permissions were granted than the ones you intended, but the reality is that the policy does not ignore your objectsKeyPattern - object-specific actions like s3:GetObject will still be limited to the resources defined in your pattern.
If you need to restrict the s3:ListBucket action to specific paths, you can add a Condition to your policy that limits the objectsKeyPattern to specific folders. For more details and examples, see the AWS documentation on bucket policies.
Attribute-Based Access Control (ABAC)
You can enable ABAC (Attribute-Based Access Control) for an S3 general purpose bucket. When ABAC is enabled for the general purpose bucket, you can use tags to manage access to the general purpose buckets as well as for cost tracking purposes. When ABAC is disabled for the general purpose buckets, you can only use tags for cost tracking purposes.
To enable ABAC on a bucket:
const bucket = new s3.Bucket(this, 'Bucket', {
abacStatus: true,
});
bucket = s3.Bucket(self, "Bucket",
abac_status=True
)
Bucket bucket = Bucket.Builder.create(this, "Bucket")
.abacStatus(true)
.build();
var bucket = new Bucket(this, "Bucket", new BucketProps {
AbacStatus = true
});
bucket := s3.NewBucket(this, jsii.String("Bucket"), &BucketProps{
AbacStatus: jsii.Boolean(true),
})
By default, if abacStatus is not specified, ABAC will not be enabled for the bucket.
For more information about ABAC and how to use it with S3, see the AWS documentation on ABAC.
AWS Foundational Security Best Practices
Enforcing SSL
To require all requests use Secure Socket Layer (SSL):
const bucket = new s3.Bucket(this, 'Bucket', {
enforceSSL: true,
});
bucket = s3.Bucket(self, "Bucket",
enforce_ssl=True
)
Bucket bucket = Bucket.Builder.create(this, "Bucket")
.enforceSSL(true)
.build();
var bucket = new Bucket(this, "Bucket", new BucketProps {
EnforceSSL = true
});
bucket := s3.NewBucket(this, jsii.String("Bucket"), &BucketProps{
EnforceSSL: jsii.Boolean(true),
})
To require a minimum TLS version for all requests:
const bucket = new s3.Bucket(this, 'Bucket', {
enforceSSL: true,
minimumTLSVersion: 1.2,
});
bucket = s3.Bucket(self, "Bucket",
enforce_ssl=True,
minimum_tls_version=1.2
)
Bucket bucket = Bucket.Builder.create(this, "Bucket")
.enforceSSL(true)
.minimumTLSVersion(1.2)
.build();
var bucket = new Bucket(this, "Bucket", new BucketProps {
EnforceSSL = true,
MinimumTLSVersion = 1.2
});
bucket := s3.NewBucket(this, jsii.String("Bucket"), &BucketProps{
EnforceSSL: jsii.Boolean(true),
MinimumTLSVersion: jsii.Number(1.2),
})
Bucket Naming
By default, CloudFormation assigns a unique bucket name. You can also specify a bucketName directly, but this creates a globally unique name that could conflict with other accounts.
Account-Regional Bucket Namespace
Using bucketNamePrefix with bucketNamespace set to ACCOUNT_REGIONAL, the bucket name is scoped to your account and region, reducing the risk of name conflicts. CloudFormation appends -<accountId>-<region>-an to the prefix to form the full name.
new s3.Bucket(this, 'MyBucket', {
bucketNamePrefix: 'my-app',
bucketNamespace: s3.BucketNamespace.ACCOUNT_REGIONAL,
});
// Resulting bucket name: my-app-123456789012-us-east-1-an
s3.Bucket(self, "MyBucket",
bucket_name_prefix="my-app",
bucket_namespace=s3.BucketNamespace.ACCOUNT_REGIONAL
)
Bucket.Builder.create(this, "MyBucket")
.bucketNamePrefix("my-app")
.bucketNamespace(BucketNamespace.ACCOUNT_REGIONAL)
.build();
new Bucket(this, "MyBucket", new BucketProps {
BucketNamePrefix = "my-app",
BucketNamespace = BucketNamespace.ACCOUNT_REGIONAL
});
s3.NewBucket(this, jsii.String("MyBucket"), &BucketProps{
BucketNamePrefix: jsii.String("my-app"),
BucketNamespace: s3.BucketNamespace_ACCOUNT_REGIONAL,
})
Note that bucketName cannot be used together with bucketNamePrefix or bucketNamespace.
For more information, see the AWS documentation on bucket namespaces.
Sharing buckets between stacks
To use a bucket in a different stack in the same CDK application, pass the object to the other stack:
/**
* Stack that defines the bucket
*/
class Producer extends Stack {
public readonly myBucket: s3.Bucket;
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const bucket = new s3.Bucket(this, 'MyBucket', {
removalPolicy: cdk.RemovalPolicy.DESTROY,
});
this.myBucket = bucket;
}
}
interface ConsumerProps extends cdk.StackProps {
userBucket: s3.IBucket;
}
/**
* Stack that consumes the bucket
*/
class Consumer extends Stack {
constructor(scope: Construct, id: string, props: ConsumerProps) {
super(scope, id, props);
const user = new iam.User(this, 'MyUser');
props.userBucket.grantReadWrite(user);
}
}
const app = new App();
const producer = new Producer(app, 'ProducerStack');
new Consumer(app, 'ConsumerStack', { userBucket: producer.myBucket });
#
# Stack that defines the bucket
#
class Producer(Stack):
def __init__(self, scope, id, *, description=None, env=None, stackName=None, tags=None, notificationArns=None, synthesizer=None, terminationProtection=None, analyticsReporting=None, crossRegionReferences=None, permissionsBoundary=None, suppressTemplateIndentation=None, propertyInjectors=None):
super().__init__(scope, id, description=description, env=env, stackName=stackName, tags=tags, notificationArns=notificationArns, synthesizer=synthesizer, terminationProtection=terminationProtection, analyticsReporting=analyticsReporting, crossRegionReferences=crossRegionReferences, permissionsBoundary=permissionsBoundary, suppressTemplateIndentation=suppressTemplateIndentation, propertyInjectors=propertyInjectors)
bucket = s3.Bucket(self, "MyBucket",
removal_policy=cdk.RemovalPolicy.DESTROY
)
self.my_bucket = bucket
#
# Stack that consumes the bucket
#
class Consumer(Stack):
def __init__(self, scope, id, *, userBucket, description=None, env=None, stackName=None, tags=None, notificationArns=None, synthesizer=None, terminationProtection=None, analyticsReporting=None, crossRegionReferences=None, permissionsBoundary=None, suppressTemplateIndentation=None, propertyInjectors=None):
super().__init__(scope, id, userBucket=userBucket, description=description, env=env, stackName=stackName, tags=tags, notificationArns=notificationArns, synthesizer=synthesizer, terminationProtection=terminationProtection, analyticsReporting=analyticsReporting, crossRegionReferences=crossRegionReferences, permissionsBoundary=permissionsBoundary, suppressTemplateIndentation=suppressTemplateIndentation, propertyInjectors=propertyInjectors)
user = iam.User(self, "MyUser")
user_bucket.grant_read_write(user)
app = App()
producer = Producer(app, "ProducerStack")
Consumer(app, "ConsumerStack", user_bucket=producer.my_bucket)
/**
* Stack that defines the bucket
*/
public class Producer extends Stack {
public final Bucket myBucket;
public Producer(Construct scope, String id) {
this(scope, id, null);
}
public Producer(Construct scope, String id, StackProps props) {
super(scope, id, props);
Bucket bucket = Bucket.Builder.create(this, "MyBucket")
.removalPolicy(RemovalPolicy.DESTROY)
.build();
this.myBucket = bucket;
}
}
public class ConsumerProps extends StackProps {
private IBucket userBucket;
public IBucket getUserBucket() {
return this.userBucket;
}
public ConsumerProps userBucket(IBucket userBucket) {
this.userBucket = userBucket;
return this;
}
}
/**
* Stack that consumes the bucket
*/
public class Consumer extends Stack {
public Consumer(Construct scope, String id, ConsumerProps props) {
super(scope, id, props);
User user = new User(this, "MyUser");
props.userBucket.grantReadWrite(user);
}
}
App app = new App();
Producer producer = new Producer(app, "ProducerStack");
new Consumer(app, "ConsumerStack", new ConsumerProps().userBucket(producer.getMyBucket()));
/**
* Stack that defines the bucket
*/
class Producer : Stack
{
public Bucket MyBucket { get; }
public Producer(Construct scope, string id, StackProps? props=null) : base(scope, id, props)
{
var bucket = new Bucket(this, "MyBucket", new BucketProps {
RemovalPolicy = RemovalPolicy.DESTROY
});
MyBucket = bucket;
}
}
class ConsumerProps : StackProps
{
public IBucket UserBucket { get; set; }
}
/**
* Stack that consumes the bucket
*/
class Consumer : Stack
{
public Consumer(Construct scope, string id, ConsumerProps props) : base(scope, id, props)
{
var user = new User(this, "MyUser");
props.UserBucket.GrantReadWrite(user);
}
}
var app = new App();
var producer = new Producer(app, "ProducerStack");
new Consumer(app, "ConsumerStack", new ConsumerProps { UserBucket = producer.MyBucket });
/**
* Stack that defines the bucket
*/
type producer struct {
Stack
myBucket Bucket
}
func newProducer(scope Construct, id *string, props StackProps) *producer {
this := &producer{}
newStack_Override(this, scope, id, props)
bucket := s3.NewBucket(this, jsii.String("MyBucket"), &BucketProps{
RemovalPolicy: cdk.RemovalPolicy_DESTROY,
})
this.myBucket = bucket
return this
}
type consumerProps struct {
StackProps
userBucket IBucket
}
/**
* Stack that consumes the bucket
*/
type consumer struct {
Stack
}
func newConsumer(scope Construct, id *string, props consumerProps) *consumer {
this := &consumer{}
newStack_Override(this, scope, id, props)
user := iam.NewUser(this, jsii.String("MyUser"))
*props.userBucket.GrantReadWrite(user)
return this
}
app := awscdk.NewApp()
producer := NewProducer(app, jsii.String("ProducerStack"))
NewConsumer(app, jsii.String("ConsumerStack"), &consumerProps{
userBucket: producer.myBucket,
})
Importing existing buckets
To import an existing bucket into your CDK application, use the Bucket.fromBucketAttributes factory method. This method accepts BucketAttributes which describes the properties of an already existing bucket:
Note that this method allows importing buckets with legacy names containing uppercase letters (A-Z) or underscores (_), which were permitted for buckets created before March 1, 2018. For buckets created after this date, uppercase letters and underscores are not allowed in the bucket name.
declare const myLambda: lambda.Function;
const bucket = s3.Bucket.fromBucketAttributes(this, 'ImportedBucket', {
bucketArn: 'arn:aws:s3:::amzn-s3-demo-bucket',
});
// now you can just call methods on the bucket
const filter: s3.NotificationKeyFilter = { prefix: 'home/myusername/*' };
bucket.addEventNotification(s3.EventType.OBJECT_CREATED, new s3n.LambdaDestination(myLambda), filter);
# my_lambda: lambda.Function
bucket = s3.Bucket.from_bucket_attributes(self, "ImportedBucket",
bucket_arn="arn:aws:s3:::amzn-s3-demo-bucket"
)
# now you can just call methods on the bucket
filter = s3.NotificationKeyFilter(prefix="home/myusername/*")
bucket.add_event_notification(s3.EventType.OBJECT_CREATED, s3n.LambdaDestination(my_lambda), filter)
Function myLambda;
IBucket bucket = Bucket.fromBucketAttributes(this, "ImportedBucket", BucketAttributes.builder()
.bucketArn("arn:aws:s3:::amzn-s3-demo-bucket")
.build());
// now you can just call methods on the bucket
NotificationKeyFilter filter = NotificationKeyFilter.builder().prefix("home/myusername/*").build();
bucket.addEventNotification(EventType.OBJECT_CREATED, new LambdaDestination(myLambda), filter);
Function myLambda;
var bucket = Bucket.FromBucketAttributes(this, "ImportedBucket", new BucketAttributes {
BucketArn = "arn:aws:s3:::amzn-s3-demo-bucket"
});
// now you can just call methods on the bucket
var filter = new NotificationKeyFilter { Prefix = "home/myusername/*" };
bucket.AddEventNotification(EventType.OBJECT_CREATED, new LambdaDestination(myLambda), filter);
var myLambda Function
bucket := s3.Bucket_FromBucketAttributes(this, jsii.String("ImportedBucket"), &BucketAttributes{
BucketArn: jsii.String("arn:aws:s3:::amzn-s3-demo-bucket"),
})
// now you can just call methods on the bucket
filter := &NotificationKeyFilter{
Prefix: jsii.String("home/myusername/*"),
}
bucket.AddEventNotification(s3.EventType_OBJECT_CREATED, s3n.NewLambdaDestination(myLambda), filter)
Alternatively, short-hand factories are available as Bucket.fromBucketName and Bucket.fromBucketArn, which will derive all bucket attributes from the bucket name or ARN respectively:
const byName = s3.Bucket.fromBucketName(this, 'BucketByName', 'amzn-s3-demo-bucket');
const byArn = s3.Bucket.fromBucketArn(this, 'BucketByArn', 'arn:aws:s3:::amzn-s3-demo-bucket');
by_name = s3.Bucket.from_bucket_name(self, "BucketByName", "amzn-s3-demo-bucket")
by_arn = s3.Bucket.from_bucket_arn(self, "BucketByArn", "arn:aws:s3:::amzn-s3-demo-bucket")
IBucket byName = Bucket.fromBucketName(this, "BucketByName", "amzn-s3-demo-bucket");
IBucket byArn = Bucket.fromBucketArn(this, "BucketByArn", "arn:aws:s3:::amzn-s3-demo-bucket");
var byName = Bucket.FromBucketName(this, "BucketByName", "amzn-s3-demo-bucket");
var byArn = Bucket.FromBucketArn(this, "BucketByArn", "arn:aws:s3:::amzn-s3-demo-bucket");
byName := s3.Bucket_FromBucketName(this, jsii.String("BucketByName"), jsii.String("amzn-s3-demo-bucket"))
byArn := s3.Bucket_FromBucketArn(this, jsii.String("BucketByArn"), jsii.String("arn:aws:s3:::amzn-s3-demo-bucket"))
The bucket's region defaults to the current stack's region, but can also be explicitly set in cases where one of the bucket's regional properties needs to contain the correct values.
const myCrossRegionBucket = s3.Bucket.fromBucketAttributes(this, 'CrossRegionImport', {
bucketArn: 'arn:aws:s3:::amzn-s3-demo-bucket',
region: 'us-east-1',
});
// myCrossRegionBucket.bucketRegionalDomainName === 'amzn-s3-demo-bucket.s3.us-east-1.amazonaws.com'
my_cross_region_bucket = s3.Bucket.from_bucket_attributes(self, "CrossRegionImport",
bucket_arn="arn:aws:s3:::amzn-s3-demo-bucket",
region="us-east-1"
)
IBucket myCrossRegionBucket = Bucket.fromBucketAttributes(this, "CrossRegionImport", BucketAttributes.builder()
.bucketArn("arn:aws:s3:::amzn-s3-demo-bucket")
.region("us-east-1")
.build());
var myCrossRegionBucket = Bucket.FromBucketAttributes(this, "CrossRegionImport", new BucketAttributes {
BucketArn = "arn:aws:s3:::amzn-s3-demo-bucket",
Region = "us-east-1"
});
myCrossRegionBucket := s3.Bucket_FromBucketAttributes(this, jsii.String("CrossRegionImport"), &BucketAttributes{
BucketArn: jsii.String("arn:aws:s3:::amzn-s3-demo-bucket"),
Region: jsii.String("us-east-1"),
})
Bucket Notifications
The Amazon S3 notification feature enables you to receive notifications when certain events happen in your bucket as described under S3 Bucket Notifications of the S3 Developer Guide.
To subscribe for bucket notifications, use the bucket.addEventNotification method. The bucket.addObjectCreatedNotification and bucket.addObjectRemovedNotification can also be used for these common use cases.
The following example will subscribe an SNS topic to be notified of all s3:ObjectCreated:* events:
const bucket = new s3.Bucket(this, 'MyBucket');
const topic = new sns.Topic(this, 'MyTopic');
bucket.addEventNotification(s3.EventType.OBJECT_CREATED, new s3n.SnsDestination(topic));
bucket = s3.Bucket(self, "MyBucket")
topic = sns.Topic(self, "MyTopic")
bucket.add_event_notification(s3.EventType.OBJECT_CREATED, s3n.SnsDestination(topic))
Bucket bucket = new Bucket(this, "MyBucket");
Topic topic = new Topic(this, "MyTopic");
bucket.addEventNotification(EventType.OBJECT_CREATED, new SnsDestination(topic));
var bucket = new Bucket(this, "MyBucket");
var topic = new Topic(this, "MyTopic");
bucket.AddEventNotification(EventType.OBJECT_CREATED, new SnsDestination(topic));
bucket := s3.NewBucket(this, jsii.String("MyBucket"))
topic := sns.NewTopic(this, jsii.String("MyTopic"))
bucket.AddEventNotification(s3.EventType_OBJECT_CREATED, s3n.NewSnsDestination(topic))
This call will also ensure that the topic policy can accept notifications for this specific bucket.
Supported S3 notification targets are exposed by the aws-cdk-lib/aws-s3-notifications package.
It is also possible to specify S3 object key filters when subscribing. The following example will notify myQueue when objects prefixed with foo/ and have the .jpg suffix are removed from the bucket.
declare const myQueue: sqs.Queue;
const bucket = new s3.Bucket(this, 'MyBucket');
bucket.addEventNotification(s3.EventType.OBJECT_REMOVED, new s3n.SqsDestination(myQueue), {
prefix: 'foo/',
suffix: '.jpg',
});
# my_queue: sqs.Queue
bucket = s3.Bucket(self, "MyBucket")
bucket.add_event_notification(s3.EventType.OBJECT_REMOVED, s3n.SqsDestination(my_queue),
prefix="foo/",
suffix=".jpg"
)
Queue myQueue;
Bucket bucket = new Bucket(this, "MyBucket");
bucket.addEventNotification(EventType.OBJECT_REMOVED, new SqsDestination(myQueue), NotificationKeyFilter.builder()
.prefix("foo/")
.suffix(".jpg")
.build());
Queue myQueue;
var bucket = new Bucket(this, "MyBucket");
bucket.AddEventNotification(EventType.OBJECT_REMOVED, new SqsDestination(myQueue), new NotificationKeyFilter {
Prefix = "foo/",
Suffix = ".jpg"
});
var myQueue Queue
bucket := s3.NewBucket(this, jsii.String("MyBucket"))
bucket.AddEventNotification(s3.EventType_OBJECT_REMOVED, s3n.NewSqsDestination(myQueue), &NotificationKeyFilter{
Prefix: jsii.String("foo/"),
Suffix: jsii.String(".jpg"),
})
Adding notifications on existing buckets:
declare const topic: sns.Topic;
const bucket = s3.Bucket.fromBucketAttributes(this, 'ImportedBucket', {
bucketArn: 'arn:aws:s3:::amzn-s3-demo-bucket',
});
bucket.addEventNotification(s3.EventType.OBJECT_CREATED, new s3n.SnsDestination(topic));
# topic: sns.Topic
bucket = s3.Bucket.from_bucket_attributes(self, "ImportedBucket",
bucket_arn="arn:aws:s3:::amzn-s3-demo-bucket"
)
bucket.add_event_notification(s3.EventType.OBJECT_CREATED, s3n.SnsDestination(topic))
Topic topic;
IBucket bucket = Bucket.fromBucketAttributes(this, "ImportedBucket", BucketAttributes.builder()
.bucketArn("arn:aws:s3:::amzn-s3-demo-bucket")
.build());
bucket.addEventNotification(EventType.OBJECT_CREATED, new SnsDestination(topic));
Topic topic;
var bucket = Bucket.FromBucketAttributes(this, "ImportedBucket", new BucketAttributes {
BucketArn = "arn:aws:s3:::amzn-s3-demo-bucket"
});
bucket.AddEventNotification(EventType.OBJECT_CREATED, new SnsDestination(topic));
var topic Topic
bucket := s3.Bucket_FromBucketAttributes(this, jsii.String("ImportedBucket"), &BucketAttributes{
BucketArn: jsii.String("arn:aws:s3:::amzn-s3-demo-bucket"),
})
bucket.AddEventNotification(s3.EventType_OBJECT_CREATED, s3n.NewSnsDestination(topic))
If you do not want for S3 to validate permissions of Amazon SQS, Amazon SNS, and Lambda destinations you can use the notificationsSkipDestinationValidation flag:
declare const myQueue: sqs.Queue;
const bucket = new s3.Bucket(this, 'MyBucket', {
notificationsSkipDestinationValidation: true,
});
bucket.addEventNotification(s3.EventType.OBJECT_REMOVED, new s3n.SqsDestination(myQueue));
# my_queue: sqs.Queue
bucket = s3.Bucket(self, "MyBucket",
notifications_skip_destination_validation=True
)
bucket.add_event_notification(s3.EventType.OBJECT_REMOVED, s3n.SqsDestination(my_queue))
Queue myQueue;
Bucket bucket = Bucket.Builder.create(this, "MyBucket")
.notificationsSkipDestinationValidation(true)
.build();
bucket.addEventNotification(EventType.OBJECT_REMOVED, new SqsDestination(myQueue));
Queue myQueue;
var bucket = new Bucket(this, "MyBucket", new BucketProps {
NotificationsSkipDestinationValidation = true
});
bucket.AddEventNotification(EventType.OBJECT_REMOVED, new SqsDestination(myQueue));
var myQueue Queue
bucket := s3.NewBucket(this, jsii.String("MyBucket"), &BucketProps{
NotificationsSkipDestinationValidation: jsii.Boolean(true),
})
bucket.AddEventNotification(s3.EventType_OBJECT_REMOVED, s3n.NewSqsDestination(myQueue))
When you add an event notification to a bucket, a custom resource is created to manage the notifications. By default, a new role is created for the Lambda function that implements this feature. If you want to use your own role instead, you should provide it in the Bucket constructor:
declare const myRole: iam.IRole;
const bucket = new s3.Bucket(this, 'MyBucket', {
notificationsHandlerRole: myRole,
});
# my_role: iam.IRole
bucket = s3.Bucket(self, "MyBucket",
notifications_handler_role=my_role
)
IRole myRole;
Bucket bucket = Bucket.Builder.create(this, "MyBucket")
.notificationsHandlerRole(myRole)
.build();
IRole myRole;
var bucket = new Bucket(this, "MyBucket", new BucketProps {
NotificationsHandlerRole = myRole
});
var myRole IRole
bucket := s3.NewBucket(this, jsii.String("MyBucket"), &BucketProps{
NotificationsHandlerRole: myRole,
})
Whatever role you provide, the CDK will try to modify it by adding the permissions from AWSLambdaBasicExecutionRole (an AWS managed policy) as well as the permissions s3:PutBucketNotification and s3:GetBucketNotification. If you’re passing an imported role, and you don’t want this to happen, configure it to be immutable:
const importedRole = iam.Role.fromRoleArn(this, 'role', 'arn:aws:iam::123456789012:role/RoleName', {
mutable: false,
});
imported_role = iam.Role.from_role_arn(self, "role", "arn:aws:iam::123456789012:role/RoleName",
mutable=False
)
IRole importedRole = Role.fromRoleArn(this, "role", "arn:aws:iam::123456789012:role/RoleName", FromRoleArnOptions.builder()
.mutable(false)
.build());
var importedRole = Role.FromRoleArn(this, "role", "arn:aws:iam::123456789012:role/RoleName", new FromRoleArnOptions {
Mutable = false
});
importedRole := iam.Role_FromRoleArn(this, jsii.String("role"), jsii.String("arn:aws:iam::123456789012:role/RoleName"), &FromRoleArnOptions{
Mutable: jsii.Boolean(false),
})
If you provide an imported immutable role, make sure that it has at least all the permissions mentioned above. Otherwise, the deployment will fail!
EventBridge notifications
Amazon S3 can send events to Amazon EventBridge whenever certain events happen in your bucket. Unlike other destinations, you don't need to select which event types you want to deliver.
The following example will enable EventBridge notifications:
const bucket = new s3.Bucket(this, 'MyEventBridgeBucket', {
eventBridgeEnabled: true,
});
bucket = s3.Bucket(self, "MyEventBridgeBucket",
event_bridge_enabled=True
)
Bucket bucket = Bucket.Builder.create(this, "MyEventBridgeBucket")
.eventBridgeEnabled(true)
.build();
var bucket = new Bucket(this, "MyEventBridgeBucket", new BucketProps {
EventBridgeEnabled = true
});
bucket := s3.NewBucket(this, jsii.String("MyEventBridgeBucket"), &BucketProps{
EventBridgeEnabled: jsii.Boolean(true),
})
Block Public Access
Use blockPublicAccess to specify block public access settings on the bucket.
Enable all block public access settings:
const bucket = new s3.Bucket(this, 'MyBlockedBucket', {
blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
});
bucket = s3.Bucket(self, "MyBlockedBucket",
block_public_access=s3.BlockPublicAccess.BLOCK_ALL
)
Bucket bucket = Bucket.Builder.create(this, "MyBlockedBucket")
.blockPublicAccess(BlockPublicAccess.BLOCK_ALL)
.build();
var bucket = new Bucket(this, "MyBlockedBucket", new BucketProps {
BlockPublicAccess = BlockPublicAccess.BLOCK_ALL
});
bucket := s3.NewBucket(this, jsii.String("MyBlockedBucket"), &BucketProps{
BlockPublicAccess: s3.BlockPublicAccess_BLOCK_ALL(),
})
Block and ignore public ACLs (other options remain unblocked):
const bucket = new s3.Bucket(this, 'MyBlockedBucket', {
blockPublicAccess: s3.BlockPublicAccess.BLOCK_ACLS_ONLY,
});
bucket = s3.Bucket(self, "MyBlockedBucket",
block_public_access=s3.BlockPublicAccess.BLOCK_ACLS_ONLY
)
Bucket bucket = Bucket.Builder.create(this, "MyBlockedBucket")
.blockPublicAccess(BlockPublicAccess.BLOCK_ACLS_ONLY)
.build();
var bucket = new Bucket(this, "MyBlockedBucket", new BucketProps {
BlockPublicAccess = BlockPublicAccess.BLOCK_ACLS_ONLY
});
bucket := s3.NewBucket(this, jsii.String("MyBlockedBucket"), &BucketProps{
BlockPublicAccess: s3.BlockPublicAccess_BLOCK_ACLS_ONLY(),
})
Alternatively, specify the settings manually (unspecified options will remain blocked):
const bucket = new s3.Bucket(this, 'MyBlockedBucket', {
blockPublicAccess: new s3.BlockPublicAccess({ blockPublicPolicy: false }),
});
bucket = s3.Bucket(self, "MyBlockedBucket",
block_public_access=s3.BlockPublicAccess(block_public_policy=False)
)
Bucket bucket = Bucket.Builder.create(this, "MyBlockedBucket")
.blockPublicAccess(BlockPublicAccess.Builder.create().blockPublicPolicy(false).build())
.build();
var bucket = new Bucket(this, "MyBlockedBucket", new BucketProps {
BlockPublicAccess = new BlockPublicAccess(new BlockPublicAccessOptions { BlockPublicPolicy = false })
});
bucket := s3.NewBucket(this, jsii.String("MyBlockedBucket"), &BucketProps{
BlockPublicAccess: s3.NewBlockPublicAccess(&BlockPublicAccessOptions{
BlockPublicPolicy: jsii.Boolean(false),
}),
})
When blockPublicPolicy is set to true, grantPublicRead() throws an error.
Public Read Access
Use publicReadAccess to allow public read access to the bucket.
Note that to enable publicReadAccess, make sure both bucket-level and account-level block public access control is disabled.
Bucket-level block public access control can be configured through blockPublicAccess property. Account-level block public access control can be configured on AWS Console -> S3 -> Block Public Access settings for this account (Navigation Panel).
const bucket = new s3.Bucket(this, 'Bucket', {
publicReadAccess: true,
blockPublicAccess: {
blockPublicPolicy: false,
blockPublicAcls: false,
ignorePublicAcls: false,
restrictPublicBuckets: false,
},
});
bucket = s3.Bucket(self, "Bucket",
public_read_access=True,
block_public_access={
"block_public_policy": False,
"block_public_acls": False,
"ignore_public_acls": False,
"restrict_public_buckets": False
}
)
Bucket bucket = Bucket.Builder.create(this, "Bucket")
.publicReadAccess(true)
.blockPublicAccess(Map.of(
"blockPublicPolicy", false,
"blockPublicAcls", false,
"ignorePublicAcls", false,
"restrictPublicBuckets", false))
.build();
var bucket = new Bucket(this, "Bucket", new BucketProps {
PublicReadAccess = true,
BlockPublicAccess = new Dictionary<string, boolean?> {
{ "blockPublicPolicy", false },
{ "blockPublicAcls", false },
{ "ignorePublicAcls", false },
{ "restrictPublicBuckets", false }
}
});
bucket := s3.NewBucket(this, jsii.String("Bucket"), &BucketProps{
PublicReadAccess: jsii.Boolean(true),
BlockPublicAccess: map[string]*bool{
"blockPublicPolicy": jsii.Boolean(false),
"blockPublicAcls": jsii.Boolean(false),
"ignorePublicAcls": jsii.Boolean(false),
"restrictPublicBuckets": jsii.Boolean(false),
},
})
Logging configuration
Use serverAccessLogsBucket to describe where server access logs are to be stored.
const accessLogsBucket = new s3.Bucket(this, 'AccessLogsBucket');
const bucket = new s3.Bucket(this, 'MyBucket', {
serverAccessLogsBucket: accessLogsBucket,
});
access_logs_bucket = s3.Bucket(self, "AccessLogsBucket")
bucket = s3.Bucket(self, "MyBucket",
server_access_logs_bucket=access_logs_bucket
)
Bucket accessLogsBucket = new Bucket(this, "AccessLogsBucket");
Bucket bucket = Bucket.Builder.create(this, "MyBucket")
.serverAccessLogsBucket(accessLogsBucket)
.build();
var accessLogsBucket = new Bucket(this, "AccessLogsBucket");
var bucket = new Bucket(this, "MyBucket", new BucketProps {
ServerAccessLogsBucket = accessLogsBucket
});
accessLogsBucket := s3.NewBucket(this, jsii.String("AccessLogsBucket"))
bucket := s3.NewBucket(this, jsii.String("MyBucket"), &BucketProps{
ServerAccessLogsBucket: accessLogsBucket,
})
It's also possible to specify a prefix for Amazon S3 to assign to all log object keys.
const accessLogsBucket = new s3.Bucket(this, 'AccessLogsBucket');
const bucket = new s3.Bucket(this, 'MyBucket', {
serverAccessLogsBucket: accessLogsBucket,
serverAccessLogsPrefix: 'logs',
});
access_logs_bucket = s3.Bucket(self, "AccessLogsBucket")
bucket = s3.Bucket(self, "MyBucket",
server_access_logs_bucket=access_logs_bucket,
server_access_logs_prefix="logs"
)
Bucket accessLogsBucket = new Bucket(this, "AccessLogsBucket");
Bucket bucket = Bucket.Builder.create(this, "MyBucket")
.serverAccessLogsBucket(accessLogsBucket)
.serverAccessLogsPrefix("logs")
.build();
var accessLogsBucket = new Bucket(this, "AccessLogsBucket");
var bucket = new Bucket(this, "MyBucket", new BucketProps {
ServerAccessLogsBucket = accessLogsBucket,
ServerAccessLogsPrefix = "logs"
});
accessLogsBucket := s3.NewBucket(this, jsii.String("AccessLogsBucket"))
bucket := s3.NewBucket(this, jsii.String("MyBucket"), &BucketProps{
ServerAccessLogsBucket: accessLogsBucket,
ServerAccessLogsPrefix: jsii.String("logs"),
})
You have two options for the log object key format. Non-date-based partitioning is the default log object key format and appears as follows:
[DestinationPrefix][YYYY]-[MM]-[DD]-[hh]-[mm]-[ss]-[UniqueString]
const accessLogsBucket = new s3.Bucket(this, 'AccessLogsBucket');
const bucket = new s3.Bucket(this, 'MyBucket', {
serverAccessLogsBucket: accessLogsBucket,
serverAccessLogsPrefix: 'logs',
// You can use a simple prefix with `TargetObjectKeyFormat.simplePrefix()`, but it is the same even if you do not specify `targetObjectKeyFormat` property.
targetObjectKeyFormat: s3.TargetObjectKeyFormat.simplePrefix(),
});
access_logs_bucket = s3.Bucket(self, "AccessLogsBucket")
bucket = s3.Bucket(self, "MyBucket",
server_access_logs_bucket=access_logs_bucket,
server_access_logs_prefix="logs",
# You can use a simple prefix with `TargetObjectKeyFormat.simplePrefix()`, but it is the same even if you do not specify `targetObjectKeyFormat` property.
target_object_key_format=s3.TargetObjectKeyFormat.simple_prefix()
)
Bucket accessLogsBucket = new Bucket(this, "AccessLogsBucket");
Bucket bucket = Bucket.Builder.create(this, "MyBucket")
.serverAccessLogsBucket(accessLogsBucket)
.serverAccessLogsPrefix("logs")
// You can use a simple prefix with `TargetObjectKeyFormat.simplePrefix()`, but it is the same even if you do not specify `targetObjectKeyFormat` property.
.targetObjectKeyFormat(TargetObjectKeyFormat.simplePrefix())
.build();
var accessLogsBucket = new Bucket(this, "AccessLogsBucket");
var bucket = new Bucket(this, "MyBucket", new BucketProps {
ServerAccessLogsBucket = accessLogsBucket,
ServerAccessLogsPrefix = "logs",
// You can use a simple prefix with `TargetObjectKeyFormat.simplePrefix()`, but it is the same even if you do not specify `targetObjectKeyFormat` property.
TargetObjectKeyFormat = TargetObjectKeyFormat.SimplePrefix()
});
accessLogsBucket := s3.NewBucket(this, jsii.String("AccessLogsBucket"))
bucket := s3.NewBucket(this, jsii.String("MyBucket"), &BucketProps{
ServerAccessLogsBucket: accessLogsBucket,
ServerAccessLogsPrefix: jsii.String("logs"),
// You can use a simple prefix with `TargetObjectKeyFormat.simplePrefix()`, but it is the same even if you do not specify `targetObjectKeyFormat` property.
TargetObjectKeyFormat: s3.TargetObjectKeyFormat_SimplePrefix(),
})
Another option is Date-based partitioning. If you choose this format, you can select either the event time or the delivery time of the log file as the date source used in the log format. This format appears as follows:
[DestinationPrefix][SourceAccountId]/[SourceRegion]/[SourceBucket]/[YYYY]/[MM]/[DD]/[YYYY]-[MM]-[DD]-[hh]-[mm]-[ss]-[UniqueString]
const accessLogsBucket = new s3.Bucket(this, 'AccessLogsBucket');
const bucket = new s3.Bucket(this, 'MyBucket', {
serverAccessLogsBucket: accessLogsBucket,
serverAccessLogsPrefix: 'logs',
targetObjectKeyFormat: s3.TargetObjectKeyFormat.partitionedPrefix(s3.PartitionDateSource.EVENT_TIME),
});
access_logs_bucket = s3.Bucket(self, "AccessLogsBucket")
bucket = s3.Bucket(self, "MyBucket",
server_access_logs_bucket=access_logs_bucket,
server_access_logs_prefix="logs",
target_object_key_format=s3.TargetObjectKeyFormat.partitioned_prefix(s3.PartitionDateSource.EVENT_TIME)
)
Bucket accessLogsBucket = new Bucket(this, "AccessLogsBucket");
Bucket bucket = Bucket.Builder.create(this, "MyBucket")
.serverAccessLogsBucket(accessLogsBucket)
.serverAccessLogsPrefix("logs")
.targetObjectKeyFormat(TargetObjectKeyFormat.partitionedPrefix(PartitionDateSource.EVENT_TIME))
.build();
var accessLogsBucket = new Bucket(this, "AccessLogsBucket");
var bucket = new Bucket(this, "MyBucket", new BucketProps {
ServerAccessLogsBucket = accessLogsBucket,
ServerAccessLogsPrefix = "logs",
TargetObjectKeyFormat = TargetObjectKeyFormat.PartitionedPrefix(PartitionDateSource.EVENT_TIME)
});
accessLogsBucket := s3.NewBucket(this, jsii.String("AccessLogsBucket"))
bucket := s3.NewBucket(this, jsii.String("MyBucket"), &BucketProps{
ServerAccessLogsBucket: accessLogsBucket,
ServerAccessLogsPrefix: jsii.String("logs"),
TargetObjectKeyFormat: s3.TargetObjectKeyFormat_PartitionedPrefix(s3.PartitionDateSource_EVENT_TIME),
})
Allowing access log delivery using a Bucket Policy (recommended)
When possible, it is recommended to use a bucket policy to grant access instead of using ACLs. When the @aws-cdk/aws-s3:serverAccessLogsUseBucketPolicy feature flag is enabled, this is done by default for server access logs. If S3 Server Access Logs are the only logs delivered to your bucket (or if all other services logging to the bucket support using bucket policy instead of ACLs), you can set object ownership to bucket owner enforced, as is recommended.
const accessLogsBucket = new s3.Bucket(this, 'AccessLogsBucket', {
objectOwnership: s3.ObjectOwnership.BUCKET_OWNER_ENFORCED,
});
const bucket = new s3.Bucket(this, 'MyBucket', {
serverAccessLogsBucket: accessLogsBucket,
serverAccessLogsPrefix: 'logs',
});
access_logs_bucket = s3.Bucket(self, "AccessLogsBucket",
object_ownership=s3.ObjectOwnership.BUCKET_OWNER_ENFORCED
)
bucket = s3.Bucket(self, "MyBucket",
server_access_logs_bucket=access_logs_bucket,
server_access_logs_prefix="logs"
)
Bucket accessLogsBucket = Bucket.Builder.create(this, "AccessLogsBucket")
.objectOwnership(ObjectOwnership.BUCKET_OWNER_ENFORCED)
.build();
Bucket bucket = Bucket.Builder.create(this, "MyBucket")
.serverAccessLogsBucket(accessLogsBucket)
.serverAccessLogsPrefix("logs")
.build();
var accessLogsBucket = new Bucket(this, "AccessLogsBucket", new BucketProps {
ObjectOwnership = ObjectOwnership.BUCKET_OWNER_ENFORCED
});
var bucket = new Bucket(this, "MyBucket", new BucketProps {
ServerAccessLogsBucket = accessLogsBucket,
ServerAccessLogsPrefix = "logs"
});
accessLogsBucket := s3.NewBucket(this, jsii.String("AccessLogsBucket"), &BucketProps{
ObjectOwnership: s3.ObjectOwnership_BUCKET_OWNER_ENFORCED,
})
bucket := s3.NewBucket(this, jsii.String("MyBucket"), &BucketProps{
ServerAccessLogsBucket: accessLogsBucket,
ServerAccessLogsPrefix: jsii.String("logs"),
})
The above code will create a new bucket policy if none exists or update the existing bucket policy to allow access log delivery.
However, there could be an edge case if the accessLogsBucket also defines a bucket policy resource using the L1 Construct. Although the mixing of L1 and L2 Constructs is not recommended, there are no mechanisms in place to prevent users from doing this at the moment.
const bucketName = "amzn-s3-demo-bucket";
const accessLogsBucket = new s3.Bucket(this, 'AccessLogsBucket', {
objectOwnership: s3.ObjectOwnership.BUCKET_OWNER_ENFORCED,
bucketName,
});
// Creating a bucket policy using L1
const bucketPolicy = new s3.CfnBucketPolicy(this, "BucketPolicy", {
bucket: bucketName,
policyDocument: {
Statement: [
{
Action: 's3:*',
Effect: 'Deny',
Principal: {
AWS: '*',
},
Resource: [
accessLogsBucket.bucketArn,
`${accessLogsBucket.bucketArn}/*`
],
},
],
Version: '2012-10-17',
},
});
// 'serverAccessLogsBucket' will create a new L2 bucket policy
// to allow log delivery and overwrite the L1 bucket policy.
const bucket = new s3.Bucket(this, 'MyBucket', {
serverAccessLogsBucket: accessLogsBucket,
serverAccessLogsPrefix: 'logs',
});
bucket_name = "amzn-s3-demo-bucket"
access_logs_bucket = s3.Bucket(self, "AccessLogsBucket",
object_ownership=s3.ObjectOwnership.BUCKET_OWNER_ENFORCED,
bucket_name=bucket_name
)
# Creating a bucket policy using L1
bucket_policy = s3.CfnBucketPolicy(self, "BucketPolicy",
bucket=bucket_name,
policy_document={
"Statement": [{
"Action": "s3:*",
"Effect": "Deny",
"Principal": {
"AWS": "*"
},
"Resource": [access_logs_bucket.bucket_arn, f"{accessLogsBucket.bucketArn}/*"
]
}
],
"Version": "2012-10-17"
}
)
# 'serverAccessLogsBucket' will create a new L2 bucket policy
# to allow log delivery and overwrite the L1 bucket policy.
bucket = s3.Bucket(self, "MyBucket",
server_access_logs_bucket=access_logs_bucket,
server_access_logs_prefix="logs"
)
String bucketName = "amzn-s3-demo-bucket";
Bucket accessLogsBucket = Bucket.Builder.create(this, "AccessLogsBucket")
.objectOwnership(ObjectOwnership.BUCKET_OWNER_ENFORCED)
.bucketName(bucketName)
.build();
// Creating a bucket policy using L1
CfnBucketPolicy bucketPolicy = CfnBucketPolicy.Builder.create(this, "BucketPolicy")
.bucket(bucketName)
.policyDocument(Map.of(
"Statement", List.of(Map.of(
"Action", "s3:*",
"Effect", "Deny",
"Principal", Map.of(
"AWS", "*"),
"Resource", List.of(accessLogsBucket.getBucketArn(), String.format("%s/*", accessLogsBucket.getBucketArn())))),
"Version", "2012-10-17"))
.build();
// 'serverAccessLogsBucket' will create a new L2 bucket policy
// to allow log delivery and overwrite the L1 bucket policy.
Bucket bucket = Bucket.Builder.create(this, "MyBucket")
.serverAccessLogsBucket(accessLogsBucket)
.serverAccessLogsPrefix("logs")
.build();
var bucketName = "amzn-s3-demo-bucket";
var accessLogsBucket = new Bucket(this, "AccessLogsBucket", new BucketProps {
ObjectOwnership = ObjectOwnership.BUCKET_OWNER_ENFORCED,
BucketName = bucketName
});
// Creating a bucket policy using L1
var bucketPolicy = new CfnBucketPolicy(this, "BucketPolicy", new CfnBucketPolicyProps {
Bucket = bucketName,
PolicyDocument = new Dictionary<string, object> {
{ "Statement", new [] { new Struct {
Action = "s3:*",
Effect = "Deny",
Principal = new Struct {
AWS = "*"
},
Resource = new [] { accessLogsBucket.BucketArn, $"{accessLogsBucket.bucketArn}/*" }
} } },
{ "Version", "2012-10-17" }
}
});
// 'serverAccessLogsBucket' will create a new L2 bucket policy
// to allow log delivery and overwrite the L1 bucket policy.
var bucket = new Bucket(this, "MyBucket", new BucketProps {
ServerAccessLogsBucket = accessLogsBucket,
ServerAccessLogsPrefix = "logs"
});
bucketName := "amzn-s3-demo-bucket"
accessLogsBucket := s3.NewBucket(this, jsii.String("AccessLogsBucket"), &BucketProps{
ObjectOwnership: s3.ObjectOwnership_BUCKET_OWNER_ENFORCED,
BucketName: jsii.String(BucketName),
})
// Creating a bucket policy using L1
bucketPolicy := s3.NewCfnBucketPolicy(this, jsii.String("BucketPolicy"), &CfnBucketPolicyProps{
Bucket: bucketName,
PolicyDocument: map[string]interface{}{
"Statement": []map[string]interface{}{
map[string]interface{}{
"Action": jsii.String("s3:*"),
"Effect": jsii.String("Deny"),
"Principal": map[string]*string{
"AWS": jsii.String("*"),
},
"Resource": []*string{
accessLogsBucket.bucketArn,
fmt.Sprintf("%v/*", accessLogsBucket.bucketArn),
},
},
},
"Version": jsii.String("2012-10-17"),
},
})
// 'serverAccessLogsBucket' will create a new L2 bucket policy
// to allow log delivery and overwrite the L1 bucket policy.
bucket := s3.NewBucket(this, jsii.String("MyBucket"), &BucketProps{
ServerAccessLogsBucket: accessLogsBucket,
ServerAccessLogsPrefix: jsii.String("logs"),
})
The above example uses the L2 Bucket Construct with the L1 CfnBucketPolicy Construct. However, when serverAccessLogsBucket is set, a new L2 Bucket Policy resource will be created which overwrites the permissions defined in the L1 Bucket Policy causing unintended behaviours.
As noted above, we highly discourage the mixed usage of L1 and L2 Constructs. The recommended approach would to define the bucket policy using addToResourcePolicy method.
const accessLogsBucket = new s3.Bucket(this, 'AccessLogsBucket', {
objectOwnership: s3.ObjectOwnership.BUCKET_OWNER_ENFORCED,
});
accessLogsBucket.addToResourcePolicy(
new iam.PolicyStatement({
actions: ['s3:*'],
resources: [accessLogsBucket.bucketArn, accessLogsBucket.arnForObjects('*')],
principals: [new iam.AnyPrincipal()],
})
)
const bucket = new s3.Bucket(this, 'MyBucket', {
serverAccessLogsBucket: accessLogsBucket,
serverAccessLogsPrefix: 'logs',
});
access_logs_bucket = s3.Bucket(self, "AccessLogsBucket",
object_ownership=s3.ObjectOwnership.BUCKET_OWNER_ENFORCED
)
access_logs_bucket.add_to_resource_policy(
iam.PolicyStatement(
actions=["s3:*"],
resources=[access_logs_bucket.bucket_arn, access_logs_bucket.arn_for_objects("*")],
principals=[iam.AnyPrincipal()]
))
bucket = s3.Bucket(self, "MyBucket",
server_access_logs_bucket=access_logs_bucket,
server_access_logs_prefix="logs"
)
Bucket accessLogsBucket = Bucket.Builder.create(this, "AccessLogsBucket")
.objectOwnership(ObjectOwnership.BUCKET_OWNER_ENFORCED)
.build();
accessLogsBucket.addToResourcePolicy(
PolicyStatement.Builder.create()
.actions(List.of("s3:*"))
.resources(List.of(accessLogsBucket.getBucketArn(), accessLogsBucket.arnForObjects("*")))
.principals(List.of(new AnyPrincipal()))
.build());
Bucket bucket = Bucket.Builder.create(this, "MyBucket")
.serverAccessLogsBucket(accessLogsBucket)
.serverAccessLogsPrefix("logs")
.build();
var accessLogsBucket = new Bucket(this, "AccessLogsBucket", new BucketProps {
ObjectOwnership = ObjectOwnership.BUCKET_OWNER_ENFORCED
});
accessLogsBucket.AddToResourcePolicy(
new PolicyStatement(new PolicyStatementProps {
Actions = new [] { "s3:*" },
Resources = new [] { accessLogsBucket.BucketArn, accessLogsBucket.ArnForObjects("*") },
Principals = new [] { new AnyPrincipal() }
}));
var bucket = new Bucket(this, "MyBucket", new BucketProps {
ServerAccessLogsBucket = accessLogsBucket,
ServerAccessLogsPrefix = "logs"
});
accessLogsBucket := s3.NewBucket(this, jsii.String("AccessLogsBucket"), &BucketProps{
ObjectOwnership: s3.ObjectOwnership_BUCKET_OWNER_ENFORCED,
})
accessLogsBucket.AddToResourcePolicy(
iam.NewPolicyStatement(&PolicyStatementProps{
Actions: []*string{
jsii.String("s3:*"),
},
Resources: []*string{
accessLogsBucket.bucketArn,
accessLogsBucket.ArnForObjects(jsii.String("*")),
},
Principals: []IPrincipal{
iam.NewAnyPrincipal(),
},
}))
bucket := s3.NewBucket(this, jsii.String("MyBucket"), &BucketProps{
ServerAccessLogsBucket: accessLogsBucket,
ServerAccessLogsPrefix: jsii.String("logs"),
})
Alternatively, users can use the L2 Bucket Policy Construct BucketPolicy.fromCfnBucketPolicy to wrap around CfnBucketPolicy Construct. This will allow the subsequent bucket policy generated by serverAccessLogsBucket usage to append to the existing bucket policy instead of overwriting.
const bucketName = "amzn-s3-demo-bucket";
const accessLogsBucket = new s3.Bucket(this, 'AccessLogsBucket', {
objectOwnership: s3.ObjectOwnership.BUCKET_OWNER_ENFORCED,
bucketName,
});
const bucketPolicy = new s3.CfnBucketPolicy(this, "BucketPolicy", {
bucket: bucketName,
policyDocument: {
Statement: [
{
Action: 's3:*',
Effect: 'Deny',
Principal: {
AWS: '*',
},
Resource: [
accessLogsBucket.bucketArn,
`${accessLogsBucket.bucketArn}/*`
],
},
],
Version: '2012-10-17',
},
});
// Wrap L1 Construct with L2 Bucket Policy Construct. Subsequent
// generated bucket policy to allow access log delivery would append
// to the current policy.
s3.BucketPolicy.fromCfnBucketPolicy(bucketPolicy);
const bucket = new s3.Bucket(this, 'MyBucket', {
serverAccessLogsBucket: accessLogsBucket,
serverAccessLogsPrefix: 'logs',
});
bucket_name = "amzn-s3-demo-bucket"
access_logs_bucket = s3.Bucket(self, "AccessLogsBucket",
object_ownership=s3.ObjectOwnership.BUCKET_OWNER_ENFORCED,
bucket_name=bucket_name
)
bucket_policy = s3.CfnBucketPolicy(self, "BucketPolicy",
bucket=bucket_name,
policy_document={
"Statement": [{
"Action": "s3:*",
"Effect": "Deny",
"Principal": {
"AWS": "*"
},
"Resource": [access_logs_bucket.bucket_arn, f"{accessLogsBucket.bucketArn}/*"
]
}
],
"Version": "2012-10-17"
}
)
# Wrap L1 Construct with L2 Bucket Policy Construct. Subsequent
# generated bucket policy to allow access log delivery would append
# to the current policy.
s3.BucketPolicy.from_cfn_bucket_policy(bucket_policy)
bucket = s3.Bucket(self, "MyBucket",
server_access_logs_bucket=access_logs_bucket,
server_access_logs_prefix="logs"
)
String bucketName = "amzn-s3-demo-bucket";
Bucket accessLogsBucket = Bucket.Builder.create(this, "AccessLogsBucket")
.objectOwnership(ObjectOwnership.BUCKET_OWNER_ENFORCED)
.bucketName(bucketName)
.build();
CfnBucketPolicy bucketPolicy = CfnBucketPolicy.Builder.create(this, "BucketPolicy")
.bucket(bucketName)
.policyDocument(Map.of(
"Statement", List.of(Map.of(
"Action", "s3:*",
"Effect", "Deny",
"Principal", Map.of(
"AWS", "*"),
"Resource", List.of(accessLogsBucket.getBucketArn(), String.format("%s/*", accessLogsBucket.getBucketArn())))),
"Version", "2012-10-17"))
.build();
// Wrap L1 Construct with L2 Bucket Policy Construct. Subsequent
// generated bucket policy to allow access log delivery would append
// to the current policy.
BucketPolicy.fromCfnBucketPolicy(bucketPolicy);
Bucket bucket = Bucket.Builder.create(this, "MyBucket")
.serverAccessLogsBucket(accessLogsBucket)
.serverAccessLogsPrefix("logs")
.build();
var bucketName = "amzn-s3-demo-bucket";
var accessLogsBucket = new Bucket(this, "AccessLogsBucket", new BucketProps {
ObjectOwnership = ObjectOwnership.BUCKET_OWNER_ENFORCED,
BucketName = bucketName
});
var bucketPolicy = new CfnBucketPolicy(this, "BucketPolicy", new CfnBucketPolicyProps {
Bucket = bucketName,
PolicyDocument = new Dictionary<string, object> {
{ "Statement", new [] { new Struct {
Action = "s3:*",
Effect = "Deny",
Principal = new Struct {
AWS = "*"
},
Resource = new [] { accessLogsBucket.BucketArn, $"{accessLogsBucket.bucketArn}/*" }
} } },
{ "Version", "2012-10-17" }
}
});
// Wrap L1 Construct with L2 Bucket Policy Construct. Subsequent
// generated bucket policy to allow access log delivery would append
// to the current policy.
BucketPolicy.FromCfnBucketPolicy(bucketPolicy);
var bucket = new Bucket(this, "MyBucket", new BucketProps {
ServerAccessLogsBucket = accessLogsBucket,
ServerAccessLogsPrefix = "logs"
});
bucketName := "amzn-s3-demo-bucket"
accessLogsBucket := s3.NewBucket(this, jsii.String("AccessLogsBucket"), &BucketProps{
ObjectOwnership: s3.ObjectOwnership_BUCKET_OWNER_ENFORCED,
BucketName: jsii.String(BucketName),
})
bucketPolicy := s3.NewCfnBucketPolicy(this, jsii.String("BucketPolicy"), &CfnBucketPolicyProps{
Bucket: bucketName,
PolicyDocument: map[string]interface{}{
"Statement": []map[string]interface{}{
map[string]interface{}{
"Action": jsii.String("s3:*"),
"Effect": jsii.String("Deny"),
"Principal": map[string]*string{
"AWS": jsii.String("*"),
},
"Resource": []*string{
accessLogsBucket.bucketArn,
fmt.Sprintf("%v/*", accessLogsBucket.bucketArn),
},
},
},
"Version": jsii.String("2012-10-17"),
},
})
// Wrap L1 Construct with L2 Bucket Policy Construct. Subsequent
// generated bucket policy to allow access log delivery would append
// to the current policy.
s3.BucketPolicy_FromCfnBucketPolicy(bucketPolicy)
bucket := s3.NewBucket(this, jsii.String("MyBucket"), &BucketProps{
ServerAccessLogsBucket: accessLogsBucket,
ServerAccessLogsPrefix: jsii.String("logs"),
})
S3 Inventory
An inventory contains a list of the objects in the source bucket and metadata for each object. The inventory lists are stored in the destination bucket as a CSV file compressed with GZIP, as an Apache optimized row columnar (ORC) file compressed with ZLIB, or as an Apache Parquet (Parquet) file compressed with Snappy.
You can configure multiple inventory lists for a bucket. You can configure what object metadata to include in the inventory, whether to list all object versions or only current versions, where to store the inventory list file output, and whether to generate the inventory on a daily or weekly basis.
const inventoryBucket = new s3.Bucket(this, 'InventoryBucket');
const dataBucket = new s3.Bucket(this, 'DataBucket', {
inventories: [
{
frequency: s3.InventoryFrequency.DAILY,
includeObjectVersions: s3.InventoryObjectVersion.CURRENT,
destination: {
bucket: inventoryBucket,
},
},
{
frequency: s3.InventoryFrequency.WEEKLY,
includeObjectVersions: s3.InventoryObjectVersion.ALL,
destination: {
bucket: inventoryBucket,
prefix: 'with-all-versions',
},
},
],
});
inventory_bucket = s3.Bucket(self, "InventoryBucket")
data_bucket = s3.Bucket(self, "DataBucket",
inventories=[s3.Inventory(
frequency=s3.InventoryFrequency.DAILY,
include_object_versions=s3.InventoryObjectVersion.CURRENT,
destination=s3.InventoryDestination(
bucket=inventory_bucket
)
), s3.Inventory(
frequency=s3.InventoryFrequency.WEEKLY,
include_object_versions=s3.InventoryObjectVersion.ALL,
destination=s3.InventoryDestination(
bucket=inventory_bucket,
prefix="with-all-versions"
)
)
]
)
Bucket inventoryBucket = new Bucket(this, "InventoryBucket");
Bucket dataBucket = Bucket.Builder.create(this, "DataBucket")
.inventories(List.of(Inventory.builder()
.frequency(InventoryFrequency.DAILY)
.includeObjectVersions(InventoryObjectVersion.CURRENT)
.destination(InventoryDestination.builder()
.bucket(inventoryBucket)
.build())
.build(), Inventory.builder()
.frequency(InventoryFrequency.WEEKLY)
.includeObjectVersions(InventoryObjectVersion.ALL)
.destination(InventoryDestination.builder()
.bucket(inventoryBucket)
.prefix("with-all-versions")
.build())
.build()))
.build();
var inventoryBucket = new Bucket(this, "InventoryBucket");
var dataBucket = new Bucket(this, "DataBucket", new BucketProps {
Inventories = new [] { new Inventory {
Frequency = InventoryFrequency.DAILY,
IncludeObjectVersions = InventoryObjectVersion.CURRENT,
Destination = new InventoryDestination {
Bucket = inventoryBucket
}
}, new Inventory {
Frequency = InventoryFrequency.WEEKLY,
IncludeObjectVersions = InventoryObjectVersion.ALL,
Destination = new InventoryDestination {
Bucket = inventoryBucket,
Prefix = "with-all-versions"
}
} }
});
inventoryBucket := s3.NewBucket(this, jsii.String("InventoryBucket"))
dataBucket := s3.NewBucket(this, jsii.String("DataBucket"), &BucketProps{
Inventories: []Inventory{
&Inventory{
Frequency: s3.InventoryFrequency_DAILY,
IncludeObjectVersions: s3.InventoryObjectVersion_CURRENT,
Destination: &InventoryDestination{
Bucket: inventoryBucket,
},
},
&Inventory{
Frequency: s3.InventoryFrequency_WEEKLY,
IncludeObjectVersions: s3.InventoryObjectVersion_ALL,
Destination: &InventoryDestination{
Bucket: inventoryBucket,
Prefix: jsii.String("with-all-versions"),
},
},
},
})
If the destination bucket is created as part of the same CDK application, the necessary permissions will be automatically added to the bucket policy. However, if you use an imported bucket (i.e Bucket.fromXXX()), you'll have to make sure it contains the following policy document:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "InventoryAndAnalyticsExamplePolicy",
"Effect": "Allow",
"Principal": { "Service": "s3.amazonaws.com" },
"Action": "s3:PutObject",
"Resource": ["arn:aws:s3:::amzn-s3-demo-destination-bucket/*"]
}
]
}
Website redirection
You can use the two following properties to specify the bucket redirection policy. Please note that these methods cannot both be applied to the same bucket.
Static redirection
You can statically redirect a to a given Bucket URL or any other host name with websiteRedirect:
const bucket = new s3.Bucket(this, 'MyRedirectedBucket', {
websiteRedirect: { hostName: 'www.example.com' },
});
bucket = s3.Bucket(self, "MyRedirectedBucket",
website_redirect=s3.RedirectTarget(host_name="www.example.com")
)
Bucket bucket = Bucket.Builder.create(this, "MyRedirectedBucket")
.websiteRedirect(RedirectTarget.builder().hostName("www.example.com").build())
.build();
var bucket = new Bucket(this, "MyRedirectedBucket", new BucketProps {
WebsiteRedirect = new RedirectTarget { HostName = "www.example.com" }
});
bucket := s3.NewBucket(this, jsii.String("MyRedirectedBucket"), &BucketProps{
WebsiteRedirect: &RedirectTarget{
HostName: jsii.String("www.example.com"),
},
})
Routing rules
Alternatively, you can also define multiple websiteRoutingRules, to define complex, conditional redirections:
const bucket = new s3.Bucket(this, 'MyRedirectedBucket', {
websiteRoutingRules: [
{
hostName: 'www.example.com',
httpRedirectCode: '302',
protocol: s3.RedirectProtocol.HTTPS,
replaceKey: s3.ReplaceKey.prefixWith('test/'),
condition: {
httpErrorCodeReturnedEquals: '200',
keyPrefixEquals: 'prefix',
},
},
],
});
bucket = s3.Bucket(self, "MyRedirectedBucket",
website_routing_rules=[s3.RoutingRule(
host_name="www.example.com",
http_redirect_code="302",
protocol=s3.RedirectProtocol.HTTPS,
replace_key=s3.ReplaceKey.prefix_with("test/"),
condition=s3.RoutingRuleCondition(
http_error_code_returned_equals="200",
key_prefix_equals="prefix"
)
)
]
)
Bucket bucket = Bucket.Builder.create(this, "MyRedirectedBucket")
.websiteRoutingRules(List.of(RoutingRule.builder()
.hostName("www.example.com")
.httpRedirectCode("302")
.protocol(RedirectProtocol.HTTPS)
.replaceKey(ReplaceKey.prefixWith("test/"))
.condition(RoutingRuleCondition.builder()
.httpErrorCodeReturnedEquals("200")
.keyPrefixEquals("prefix")
.build())
.build()))
.build();
var bucket = new Bucket(this, "MyRedirectedBucket", new BucketProps {
WebsiteRoutingRules = new [] { new RoutingRule {
HostName = "www.example.com",
HttpRedirectCode = "302",
Protocol = RedirectProtocol.HTTPS,
ReplaceKey = ReplaceKey.PrefixWith("test/"),
Condition = new RoutingRuleCondition {
HttpErrorCodeReturnedEquals = "200",
KeyPrefixEquals = "prefix"
}
} }
});
bucket := s3.NewBucket(this, jsii.String("MyRedirectedBucket"), &BucketProps{
WebsiteRoutingRules: []RoutingRule{
&RoutingRule{
HostName: jsii.String("www.example.com"),
HttpRedirectCode: jsii.String("302"),
Protocol: s3.RedirectProtocol_HTTPS,
ReplaceKey: s3.ReplaceKey_PrefixWith(jsii.String("test/")),
Condition: &RoutingRuleCondition{
HttpErrorCodeReturnedEquals: jsii.String("200"),
KeyPrefixEquals: jsii.String("prefix"),
},
},
},
})
Filling the bucket as part of deployment
To put files into a bucket as part of a deployment (for example, to host a website), see the aws-cdk-lib/aws-s3-deployment package, which provides a resource that can do just that.
The URL for objects
S3 provides two types of URLs for accessing objects via HTTP(S). Path-Style and Virtual Hosted-Style URL. Path-Style is a classic way and will be deprecated. We recommend to use Virtual Hosted-Style URL for newly made bucket.
You can generate both of them.
const bucket = new s3.Bucket(this, 'MyBucket');
bucket.urlForObject('objectname'); // Path-Style URL
bucket.virtualHostedUrlForObject('objectname'); // Virtual Hosted-Style URL
bucket.virtualHostedUrlForObject('objectname', { regional: false }); // Virtual Hosted-Style URL but non-regional
bucket = s3.Bucket(self, "MyBucket")
bucket.url_for_object("objectname") # Path-Style URL
bucket.virtual_hosted_url_for_object("objectname") # Virtual Hosted-Style URL
bucket.virtual_hosted_url_for_object("objectname", regional=False)
Bucket bucket = new Bucket(this, "MyBucket");
bucket.urlForObject("objectname"); // Path-Style URL
bucket.virtualHostedUrlForObject("objectname"); // Virtual Hosted-Style URL
bucket.virtualHostedUrlForObject("objectname", VirtualHostedStyleUrlOptions.builder().regional(false).build());
var bucket = new Bucket(this, "MyBucket");
bucket.UrlForObject("objectname"); // Path-Style URL
bucket.VirtualHostedUrlForObject("objectname"); // Virtual Hosted-Style URL
bucket.VirtualHostedUrlForObject("objectname", new VirtualHostedStyleUrlOptions { Regional = false });
bucket := s3.NewBucket(this, jsii.String("MyBucket"))
bucket.UrlForObject(jsii.String("objectname")) // Path-Style URL
bucket.VirtualHostedUrlForObject(jsii.String("objectname")) // Virtual Hosted-Style URL
bucket.VirtualHostedUrlForObject(jsii.String("objectname"), &VirtualHostedStyleUrlOptions{
Regional: jsii.Boolean(false),
})
Object Ownership
You can use one of following properties to specify the bucket object Ownership.
Object writer
The Uploading account will own the object.
new s3.Bucket(this, 'MyBucket', {
objectOwnership: s3.ObjectOwnership.OBJECT_WRITER,
});
s3.Bucket(self, "MyBucket",
object_ownership=s3.ObjectOwnership.OBJECT_WRITER
)
Bucket.Builder.create(this, "MyBucket")
.objectOwnership(ObjectOwnership.OBJECT_WRITER)
.build();
new Bucket(this, "MyBucket", new BucketProps {
ObjectOwnership = ObjectOwnership.OBJECT_WRITER
});
s3.NewBucket(this, jsii.String("MyBucket"), &BucketProps{
ObjectOwnership: s3.ObjectOwnership_OBJECT_WRITER,
})
Bucket owner preferred
The bucket owner will own the object if the object is uploaded with the bucket-owner-full-control canned ACL. Without this setting and canned ACL, the object is uploaded and remains owned by the uploading account.
new s3.Bucket(this, 'MyBucket', {
objectOwnership: s3.ObjectOwnership.BUCKET_OWNER_PREFERRED,
});
s3.Bucket(self, "MyBucket",
object_ownership=s3.ObjectOwnership.BUCKET_OWNER_PREFERRED
)
Bucket.Builder.create(this, "MyBucket")
.objectOwnership(ObjectOwnership.BUCKET_OWNER_PREFERRED)
.build();
new Bucket(this, "MyBucket", new BucketProps {
ObjectOwnership = ObjectOwnership.BUCKET_OWNER_PREFERRED
});
s3.NewBucket(this, jsii.String("MyBucket"), &BucketProps{
ObjectOwnership: s3.ObjectOwnership_BUCKET_OWNER_PREFERRED,
})
Bucket owner enforced (recommended)
ACLs are disabled, and the bucket owner automatically owns and has full control over every object in the bucket. ACLs no longer affect permissions to data in the S3 bucket. The bucket uses policies to define access control.
new s3.Bucket(this, 'MyBucket', {
objectOwnership: s3.ObjectOwnership.BUCKET_OWNER_ENFORCED,
});
s3.Bucket(self, "MyBucket",
object_ownership=s3.ObjectOwnership.BUCKET_OWNER_ENFORCED
)
Bucket.Builder.create(this, "MyBucket")
.objectOwnership(ObjectOwnership.BUCKET_OWNER_ENFORCED)
.build();
new Bucket(this, "MyBucket", new BucketProps {
ObjectOwnership = ObjectOwnership.BUCKET_OWNER_ENFORCED
});
s3.NewBucket(this, jsii.String("MyBucket"), &BucketProps{
ObjectOwnership: s3.ObjectOwnership_BUCKET_OWNER_ENFORCED,
})
Some services may not not support log delivery to buckets that have object ownership set to bucket owner enforced, such as S3 buckets using ACLs or CloudFront Distributions.
Bucket deletion
When a bucket is removed from a stack (or the stack is deleted), the S3 bucket will be removed according to its removal policy (which by default will simply orphan the bucket and leave it in your AWS account). If the removal policy is set to RemovalPolicy.DESTROY, the bucket will be deleted as long as it does not contain any objects.
To override this and force all objects to get deleted during bucket deletion, enable theautoDeleteObjects option.
When autoDeleteObjects is enabled, s3:PutBucketPolicy is added to the bucket policy. This is done to allow the custom resource this feature is built on to add a deny policy for s3:PutObject to the bucket policy when a delete stack event occurs. Adding this deny policy prevents new objects from being written to the bucket. Doing this prevents race conditions with external bucket writers during the deletion process.
const bucket = new s3.Bucket(this, 'MyTempFileBucket', {
removalPolicy: cdk.RemovalPolicy.DESTROY,
autoDeleteObjects: true,
});
bucket = s3.Bucket(self, "MyTempFileBucket",
removal_policy=cdk.RemovalPolicy.DESTROY,
auto_delete_objects=True
)
Bucket bucket = Bucket.Builder.create(this, "MyTempFileBucket")
.removalPolicy(RemovalPolicy.DESTROY)
.autoDeleteObjects(true)
.build();
var bucket = new Bucket(this, "MyTempFileBucket", new BucketProps {
RemovalPolicy = RemovalPolicy.DESTROY,
AutoDeleteObjects = true
});
bucket := s3.NewBucket(this, jsii.String("MyTempFileBucket"), &BucketProps{
RemovalPolicy: cdk.RemovalPolicy_DESTROY,
AutoDeleteObjects: jsii.Boolean(true),
})
Warning if you have deployed a bucket with autoDeleteObjects: true, switching this to false in a CDK version before 1.126.0 will lead to all objects in the bucket being deleted. Be sure to update your bucket resources by deploying with CDK version 1.126.0 or later before switching this value to false.
Transfer Acceleration
Transfer Acceleration can be configured to enable fast, easy, and secure transfers of files over long distances:
const bucket = new s3.Bucket(this, 'MyBucket', {
transferAcceleration: true,
});
bucket = s3.Bucket(self, "MyBucket",
transfer_acceleration=True
)
Bucket bucket = Bucket.Builder.create(this, "MyBucket")
.transferAcceleration(true)
.build();
var bucket = new Bucket(this, "MyBucket", new BucketProps {
TransferAcceleration = true
});
bucket := s3.NewBucket(this, jsii.String("MyBucket"), &BucketProps{
TransferAcceleration: jsii.Boolean(true),
})
To access the bucket that is enabled for Transfer Acceleration, you must use a special endpoint. The URL can be generated using method transferAccelerationUrlForObject:
const bucket = new s3.Bucket(this, 'MyBucket', {
transferAcceleration: true,
});
bucket.transferAccelerationUrlForObject('objectname');
bucket = s3.Bucket(self, "MyBucket",
transfer_acceleration=True
)
bucket.transfer_acceleration_url_for_object("objectname")
Bucket bucket = Bucket.Builder.create(this, "MyBucket")
.transferAcceleration(true)
.build();
bucket.transferAccelerationUrlForObject("objectname");
var bucket = new Bucket(this, "MyBucket", new BucketProps {
TransferAcceleration = true
});
bucket.TransferAccelerationUrlForObject("objectname");
bucket := s3.NewBucket(this, jsii.String("MyBucket"), &BucketProps{
TransferAcceleration: jsii.Boolean(true),
})
bucket.TransferAccelerationUrlForObject(jsii.String("objectname"))
Intelligent Tiering
Intelligent Tiering can be configured to automatically move files to glacier:
new s3.Bucket(this, 'MyBucket', {
intelligentTieringConfigurations: [
{
name: 'foo',
prefix: 'folder/name',
archiveAccessTierTime: Duration.days(90),
deepArchiveAccessTierTime: Duration.days(180),
tags: [{ key: 'tagname', value: 'tagvalue' }],
},
],
});
s3.Bucket(self, "MyBucket",
intelligent_tiering_configurations=[s3.IntelligentTieringConfiguration(
name="foo",
prefix="folder/name",
archive_access_tier_time=Duration.days(90),
deep_archive_access_tier_time=Duration.days(180),
tags=[s3.Tag(key="tagname", value="tagvalue")]
)
]
)
Bucket.Builder.create(this, "MyBucket")
.intelligentTieringConfigurations(List.of(IntelligentTieringConfiguration.builder()
.name("foo")
.prefix("folder/name")
.archiveAccessTierTime(Duration.days(90))
.deepArchiveAccessTierTime(Duration.days(180))
.tags(List.of(Tag.builder().key("tagname").value("tagvalue").build()))
.build()))
.build();
new Bucket(this, "MyBucket", new BucketProps {
IntelligentTieringConfigurations = new [] { new IntelligentTieringConfiguration {
Name = "foo",
Prefix = "folder/name",
ArchiveAccessTierTime = Duration.Days(90),
DeepArchiveAccessTierTime = Duration.Days(180),
Tags = new [] { new Tag { Key = "tagname", Value = "tagvalue" } }
} }
});
s3.NewBucket(this, jsii.String("MyBucket"), &BucketProps{
IntelligentTieringConfigurations: []IntelligentTieringConfiguration{
&IntelligentTieringConfiguration{
Name: jsii.String("foo"),
Prefix: jsii.String("folder/name"),
ArchiveAccessTierTime: awscdk.Duration_Days(jsii.Number(90)),
DeepArchiveAccessTierTime: awscdk.Duration_*Days(jsii.Number(180)),
Tags: []Tag{
&Tag{
Key: jsii.String("tagname"),
Value: jsii.String("tagvalue"),
},
},
},
},
})
Lifecycle Rule
Managing lifecycle can be configured transition or expiration actions.
const bucket = new s3.Bucket(this, 'MyBucket', {
lifecycleRules: [
{
abortIncompleteMultipartUploadAfter: Duration.minutes(30),
enabled: false,
expiration: Duration.days(30),
expirationDate: new Date(),
expiredObjectDeleteMarker: false,
id: 'id',
noncurrentVersionExpiration: Duration.days(30),
// the properties below are optional
noncurrentVersionsToRetain: 123,
noncurrentVersionTransitions: [
{
storageClass: s3.StorageClass.GLACIER,
transitionAfter: Duration.days(30),
// the properties below are optional
noncurrentVersionsToRetain: 123,
},
],
objectSizeGreaterThan: 500,
prefix: 'prefix',
objectSizeLessThan: 10000,
transitions: [
{
storageClass: s3.StorageClass.GLACIER,
// exactly one of transitionAfter or transitionDate must be specified
transitionAfter: Duration.days(30),
// transitionDate: new Date(), // cannot specify both
},
],
},
],
});
bucket = s3.Bucket(self, "MyBucket",
lifecycle_rules=[s3.LifecycleRule(
abort_incomplete_multipart_upload_after=Duration.minutes(30),
enabled=False,
expiration=Duration.days(30),
expiration_date=Date(),
expired_object_delete_marker=False,
id="id",
noncurrent_version_expiration=Duration.days(30),
# the properties below are optional
noncurrent_versions_to_retain=123,
noncurrent_version_transitions=[s3.NoncurrentVersionTransition(
storage_class=s3.StorageClass.GLACIER,
transition_after=Duration.days(30),
# the properties below are optional
noncurrent_versions_to_retain=123
)
],
object_size_greater_than=500,
prefix="prefix",
object_size_less_than=10000,
transitions=[s3.Transition(
storage_class=s3.StorageClass.GLACIER,
# exactly one of transitionAfter or transitionDate must be specified
transition_after=Duration.days(30)
)
]
)
]
)
Bucket bucket = Bucket.Builder.create(this, "MyBucket")
.lifecycleRules(List.of(LifecycleRule.builder()
.abortIncompleteMultipartUploadAfter(Duration.minutes(30))
.enabled(false)
.expiration(Duration.days(30))
.expirationDate(new Date())
.expiredObjectDeleteMarker(false)
.id("id")
.noncurrentVersionExpiration(Duration.days(30))
// the properties below are optional
.noncurrentVersionsToRetain(123)
.noncurrentVersionTransitions(List.of(NoncurrentVersionTransition.builder()
.storageClass(StorageClass.GLACIER)
.transitionAfter(Duration.days(30))
// the properties below are optional
.noncurrentVersionsToRetain(123)
.build()))
.objectSizeGreaterThan(500)
.prefix("prefix")
.objectSizeLessThan(10000)
.transitions(List.of(Transition.builder()
.storageClass(StorageClass.GLACIER)
// exactly one of transitionAfter or transitionDate must be specified
.transitionAfter(Duration.days(30))
.build()))
.build()))
.build();
var bucket = new Bucket(this, "MyBucket", new BucketProps {
LifecycleRules = new [] { new LifecycleRule {
AbortIncompleteMultipartUploadAfter = Duration.Minutes(30),
Enabled = false,
Expiration = Duration.Days(30),
ExpirationDate = new Date(),
ExpiredObjectDeleteMarker = false,
Id = "id",
NoncurrentVersionExpiration = Duration.Days(30),
// the properties below are optional
NoncurrentVersionsToRetain = 123,
NoncurrentVersionTransitions = new [] { new NoncurrentVersionTransition {
StorageClass = StorageClass.GLACIER,
TransitionAfter = Duration.Days(30),
// the properties below are optional
NoncurrentVersionsToRetain = 123
} },
ObjectSizeGreaterThan = 500,
Prefix = "prefix",
ObjectSizeLessThan = 10000,
Transitions = new [] { new Transition {
StorageClass = StorageClass.GLACIER,
// exactly one of transitionAfter or transitionDate must be specified
TransitionAfter = Duration.Days(30)
} }
} }
});
bucket := s3.NewBucket(this, jsii.String("MyBucket"), &BucketProps{
LifecycleRules: []LifecycleRule{
&LifecycleRule{
AbortIncompleteMultipartUploadAfter: awscdk.Duration_Minutes(jsii.Number(30)),
Enabled: jsii.Boolean(false),
Expiration: awscdk.Duration_Days(jsii.Number(30)),
ExpirationDate: NewDate(),
ExpiredObjectDeleteMarker: jsii.Boolean(false),
Id: jsii.String("id"),
NoncurrentVersionExpiration: awscdk.Duration_*Days(jsii.Number(30)),
// the properties below are optional
NoncurrentVersionsToRetain: jsii.Number(123),
NoncurrentVersionTransitions: []NoncurrentVersionTransition{
&NoncurrentVersionTransition{
StorageClass: s3.StorageClass_GLACIER(),
TransitionAfter: awscdk.Duration_*Days(jsii.Number(30)),
// the properties below are optional
NoncurrentVersionsToRetain: jsii.Number(123),
},
},
ObjectSizeGreaterThan: jsii.Number(500),
Prefix: jsii.String("prefix"),
ObjectSizeLessThan: jsii.Number(10000),
Transitions: []Transition{
&Transition{
StorageClass: s3.StorageClass_GLACIER(),
// exactly one of transitionAfter or transitionDate must be specified
TransitionAfter: awscdk.Duration_*Days(jsii.Number(30)),
},
},
},
},
})
To indicate which default minimum object size behavior is applied to the lifecycle configuration, use the transitionDefaultMinimumObjectSize property.
The default value of the property before September 2024 is TransitionDefaultMinimumObjectSize.VARIES_BY_STORAGE_CLASS that allows objects smaller than 128 KB to be transitioned only to the S3 Glacier and S3 Glacier Deep Archive storage classes, otherwise TransitionDefaultMinimumObjectSize.ALL_STORAGE_CLASSES_128_K that prevents objects smaller than 128 KB from being transitioned to any storage class.
To customize the minimum object size for any transition you can add a filter that specifies a custom objectSizeGreaterThan or objectSizeLessThan for lifecycleRules property. Custom filters always take precedence over the default transition behavior.
new s3.Bucket(this, 'MyBucket', {
transitionDefaultMinimumObjectSize: s3.TransitionDefaultMinimumObjectSize.VARIES_BY_STORAGE_CLASS,
lifecycleRules: [
{
transitions: [{
storageClass: s3.StorageClass.DEEP_ARCHIVE,
transitionAfter: Duration.days(30),
}],
},
{
objectSizeLessThan: 300000,
objectSizeGreaterThan: 200000,
transitions: [{
storageClass: s3.StorageClass.ONE_ZONE_INFREQUENT_ACCESS,
transitionAfter: Duration.days(30),
}],
},
],
});
s3.Bucket(self, "MyBucket",
transition_default_minimum_object_size=s3.TransitionDefaultMinimumObjectSize.VARIES_BY_STORAGE_CLASS,
lifecycle_rules=[s3.LifecycleRule(
transitions=[s3.Transition(
storage_class=s3.StorageClass.DEEP_ARCHIVE,
transition_after=Duration.days(30)
)]
), s3.LifecycleRule(
object_size_less_than=300000,
object_size_greater_than=200000,
transitions=[s3.Transition(
storage_class=s3.StorageClass.ONE_ZONE_INFREQUENT_ACCESS,
transition_after=Duration.days(30)
)]
)
]
)
Bucket.Builder.create(this, "MyBucket")
.transitionDefaultMinimumObjectSize(TransitionDefaultMinimumObjectSize.VARIES_BY_STORAGE_CLASS)
.lifecycleRules(List.of(LifecycleRule.builder()
.transitions(List.of(Transition.builder()
.storageClass(StorageClass.DEEP_ARCHIVE)
.transitionAfter(Duration.days(30))
.build()))
.build(), LifecycleRule.builder()
.objectSizeLessThan(300000)
.objectSizeGreaterThan(200000)
.transitions(List.of(Transition.builder()
.storageClass(StorageClass.ONE_ZONE_INFREQUENT_ACCESS)
.transitionAfter(Duration.days(30))
.build()))
.build()))
.build();
new Bucket(this, "MyBucket", new BucketProps {
TransitionDefaultMinimumObjectSize = TransitionDefaultMinimumObjectSize.VARIES_BY_STORAGE_CLASS,
LifecycleRules = new [] { new LifecycleRule {
Transitions = new [] { new Transition {
StorageClass = StorageClass.DEEP_ARCHIVE,
TransitionAfter = Duration.Days(30)
} }
}, new LifecycleRule {
ObjectSizeLessThan = 300000,
ObjectSizeGreaterThan = 200000,
Transitions = new [] { new Transition {
StorageClass = StorageClass.ONE_ZONE_INFREQUENT_ACCESS,
TransitionAfter = Duration.Days(30)
} }
} }
});
s3.NewBucket(this, jsii.String("MyBucket"), &BucketProps{
TransitionDefaultMinimumObjectSize: s3.TransitionDefaultMinimumObjectSize_VARIES_BY_STORAGE_CLASS,
LifecycleRules: []LifecycleRule{
&LifecycleRule{
Transitions: []Transition{
&Transition{
StorageClass: s3.StorageClass_DEEP_ARCHIVE(),
TransitionAfter: awscdk.Duration_Days(jsii.Number(30)),
},
},
},
&LifecycleRule{
ObjectSizeLessThan: jsii.Number(300000),
ObjectSizeGreaterThan: jsii.Number(200000),
Transitions: []Transition{
&Transition{
StorageClass: s3.StorageClass_ONE_ZONE_INFREQUENT_ACCESS(),
TransitionAfter: awscdk.Duration_*Days(jsii.Number(30)),
},
},
},
},
})
Object Lock Configuration
Object Lock can be configured to enable a write-once-read-many model for an S3 bucket. Object Lock must be configured when a bucket is created; if a bucket is created without Object Lock, it cannot be enabled later via the CDK.
Object Lock can be enabled on an S3 bucket by specifying:
const bucket = new s3.Bucket(this, 'MyBucket', {
objectLockEnabled: true,
});
bucket = s3.Bucket(self, "MyBucket",
object_lock_enabled=True
)
Bucket bucket = Bucket.Builder.create(this, "MyBucket")
.objectLockEnabled(true)
.build();
var bucket = new Bucket(this, "MyBucket", new BucketProps {
ObjectLockEnabled = true
});
bucket := s3.NewBucket(this, jsii.String("MyBucket"), &BucketProps{
ObjectLockEnabled: jsii.Boolean(true),
})
Usually, it is desired to not just enable Object Lock for a bucket but to also configure a retention mode and a retention period. These can be specified by providing objectLockDefaultRetention:
// Configure for governance mode with a duration of 7 years
new s3.Bucket(this, 'Bucket1', {
objectLockDefaultRetention: s3.ObjectLockRetention.governance(Duration.days(7 * 365)),
});
// Configure for compliance mode with a duration of 1 year
new s3.Bucket(this, 'Bucket2', {
objectLockDefaultRetention: s3.ObjectLockRetention.compliance(Duration.days(365)),
});
# Configure for governance mode with a duration of 7 years
s3.Bucket(self, "Bucket1",
object_lock_default_retention=s3.ObjectLockRetention.governance(Duration.days(7 * 365))
)
# Configure for compliance mode with a duration of 1 year
s3.Bucket(self, "Bucket2",
object_lock_default_retention=s3.ObjectLockRetention.compliance(Duration.days(365))
)
// Configure for governance mode with a duration of 7 years
// Configure for governance mode with a duration of 7 years
Bucket.Builder.create(this, "Bucket1")
.objectLockDefaultRetention(ObjectLockRetention.governance(Duration.days(7 * 365)))
.build();
// Configure for compliance mode with a duration of 1 year
// Configure for compliance mode with a duration of 1 year
Bucket.Builder.create(this, "Bucket2")
.objectLockDefaultRetention(ObjectLockRetention.compliance(Duration.days(365)))
.build();
// Configure for governance mode with a duration of 7 years
// Configure for governance mode with a duration of 7 years
new Bucket(this, "Bucket1", new BucketProps {
ObjectLockDefaultRetention = ObjectLockRetention.Governance(Duration.Days(7 * 365))
});
// Configure for compliance mode with a duration of 1 year
// Configure for compliance mode with a duration of 1 year
new Bucket(this, "Bucket2", new BucketProps {
ObjectLockDefaultRetention = ObjectLockRetention.Compliance(Duration.Days(365))
});
// Configure for governance mode with a duration of 7 years
// Configure for governance mode with a duration of 7 years
s3.NewBucket(this, jsii.String("Bucket1"), &BucketProps{
ObjectLockDefaultRetention: s3.ObjectLockRetention_Governance(awscdk.Duration_Days(jsii.Number(7 * 365))),
})
// Configure for compliance mode with a duration of 1 year
// Configure for compliance mode with a duration of 1 year
s3.NewBucket(this, jsii.String("Bucket2"), &BucketProps{
ObjectLockDefaultRetention: s3.ObjectLockRetention_Compliance(awscdk.Duration_*Days(jsii.Number(365))),
})
Replicating Objects
You can use replicating objects to enable automatic, asynchronous copying of objects across Amazon S3 buckets. Buckets that are configured for object replication can be owned by the same AWS account or by different accounts. You can replicate objects to a single destination bucket or to multiple destination buckets. The destination buckets can be in different AWS Regions or within the same Region as the source bucket.
To replicate objects to a destination bucket, you can specify the replicationRules property:
declare const destinationBucket1: s3.IBucket;
declare const destinationBucket2: s3.IBucket;
declare const replicationRole: iam.IRole;
declare const encryptionKey: kms.IKey;
declare const destinationEncryptionKey: kms.IKey;
const sourceBucket = new s3.Bucket(this, 'SourceBucket', {
// Versioning must be enabled on both the source and destination bucket
versioned: true,
// Optional. Specify the KMS key to use for encrypts objects in the source bucket.
encryptionKey,
// Optional. If not specified, a new role will be created.
replicationRole,
replicationRules: [
{
// The destination bucket for the replication rule.
destination: destinationBucket1,
// The priority of the rule.
// Amazon S3 will attempt to replicate objects according to all replication rules.
// However, if there are two or more rules with the same destination bucket, then objects will be replicated according to the rule with the highest priority.
// The higher the number, the higher the priority.
// It is essential to specify priority explicitly when the replication configuration has multiple rules.
priority: 1,
},
{
destination: destinationBucket2,
priority: 2,
// Whether to specify S3 Replication Time Control (S3 RTC).
// S3 RTC replicates most objects that you upload to Amazon S3 in seconds,
// and 99.99 percent of those objects within specified time.
replicationTimeControl: s3.ReplicationTimeValue.FIFTEEN_MINUTES,
// Whether to enable replication metrics about S3 RTC.
// If set, metrics will be output to indicate whether replication by S3 RTC took longer than the configured time.
metrics: s3.ReplicationTimeValue.FIFTEEN_MINUTES,
// The kms key to use for the destination bucket.
kmsKey: destinationEncryptionKey,
// The storage class to use for the destination bucket.
storageClass: s3.StorageClass.INFREQUENT_ACCESS,
// Whether to replicate objects with SSE-KMS encryption.
sseKmsEncryptedObjects: false,
// Whether to replicate modifications on replicas.
replicaModifications: true,
// Whether to replicate delete markers.
// This property cannot be enabled if the replication rule has a tag filter.
deleteMarkerReplication: false,
// The ID of the rule.
id: 'full-settings-rule',
// The object filter for the rule.
filter: {
// The prefix filter for the rule.
prefix: 'prefix',
// The tag filter for the rule.
tags: [
{
key: 'tagKey',
value: 'tagValue',
},
],
}
},
],
});
// Grant permissions to the replication role.
// This method is not required if you choose to use an auto-generated replication role or manually grant permissions.
sourceBucket.grantReplicationPermission(replicationRole, {
// Optional. Specify the KMS key to use for decrypting objects in the source bucket.
sourceDecryptionKey: encryptionKey,
destinations: [
{ bucket: destinationBucket1 },
{ bucket: destinationBucket2, encryptionKey: destinationEncryptionKey },
],
// The 'encryptionKey' property within the 'destinations' array is optional.
// If not specified for a destination bucket, this method assumes that
// given destination bucket is not encrypted.
});
# destination_bucket1: s3.IBucket
# destination_bucket2: s3.IBucket
# replication_role: iam.IRole
# encryption_key: kms.IKey
# destination_encryption_key: kms.IKey
source_bucket = s3.Bucket(self, "SourceBucket",
# Versioning must be enabled on both the source and destination bucket
versioned=True,
# Optional. Specify the KMS key to use for encrypts objects in the source bucket.
encryption_key=encryption_key,
# Optional. If not specified, a new role will be created.
replication_role=replication_role,
replication_rules=[s3.ReplicationRule(
# The destination bucket for the replication rule.
destination=destination_bucket1,
# The priority of the rule.
# Amazon S3 will attempt to replicate objects according to all replication rules.
# However, if there are two or more rules with the same destination bucket, then objects will be replicated according to the rule with the highest priority.
# The higher the number, the higher the priority.
# It is essential to specify priority explicitly when the replication configuration has multiple rules.
priority=1
), s3.ReplicationRule(
destination=destination_bucket2,
priority=2,
# Whether to specify S3 Replication Time Control (S3 RTC).
# S3 RTC replicates most objects that you upload to Amazon S3 in seconds,
# and 99.99 percent of those objects within specified time.
replication_time_control=s3.ReplicationTimeValue.FIFTEEN_MINUTES,
# Whether to enable replication metrics about S3 RTC.
# If set, metrics will be output to indicate whether replication by S3 RTC took longer than the configured time.
metrics=s3.ReplicationTimeValue.FIFTEEN_MINUTES,
# The kms key to use for the destination bucket.
kms_key=destination_encryption_key,
# The storage class to use for the destination bucket.
storage_class=s3.StorageClass.INFREQUENT_ACCESS,
# Whether to replicate objects with SSE-KMS encryption.
sse_kms_encrypted_objects=False,
# Whether to replicate modifications on replicas.
replica_modifications=True,
# Whether to replicate delete markers.
# This property cannot be enabled if the replication rule has a tag filter.
delete_marker_replication=False,
# The ID of the rule.
id="full-settings-rule",
# The object filter for the rule.
filter=s3.Filter(
# The prefix filter for the rule.
prefix="prefix",
# The tag filter for the rule.
tags=[s3.Tag(
key="tagKey",
value="tagValue"
)
]
)
)
]
)
# Grant permissions to the replication role.
# This method is not required if you choose to use an auto-generated replication role or manually grant permissions.
source_bucket.grant_replication_permission(replication_role,
# Optional. Specify the KMS key to use for decrypting objects in the source bucket.
source_decryption_key=encryption_key,
destinations=[s3.GrantReplicationPermissionDestinationProps(bucket=destination_bucket1), s3.GrantReplicationPermissionDestinationProps(bucket=destination_bucket2, encryption_key=destination_encryption_key)
]
)
IBucket destinationBucket1;
IBucket destinationBucket2;
IRole replicationRole;
IKey encryptionKey;
IKey destinationEncryptionKey;
Bucket sourceBucket = Bucket.Builder.create(this, "SourceBucket")
// Versioning must be enabled on both the source and destination bucket
.versioned(true)
// Optional. Specify the KMS key to use for encrypts objects in the source bucket.
.encryptionKey(encryptionKey)
// Optional. If not specified, a new role will be created.
.replicationRole(replicationRole)
.replicationRules(List.of(ReplicationRule.builder()
// The destination bucket for the replication rule.
.destination(destinationBucket1)
// The priority of the rule.
// Amazon S3 will attempt to replicate objects according to all replication rules.
// However, if there are two or more rules with the same destination bucket, then objects will be replicated according to the rule with the highest priority.
// The higher the number, the higher the priority.
// It is essential to specify priority explicitly when the replication configuration has multiple rules.
.priority(1)
.build(), ReplicationRule.builder()
.destination(destinationBucket2)
.priority(2)
// Whether to specify S3 Replication Time Control (S3 RTC).
// S3 RTC replicates most objects that you upload to Amazon S3 in seconds,
// and 99.99 percent of those objects within specified time.
.replicationTimeControl(ReplicationTimeValue.FIFTEEN_MINUTES)
// Whether to enable replication metrics about S3 RTC.
// If set, metrics will be output to indicate whether replication by S3 RTC took longer than the configured time.
.metrics(ReplicationTimeValue.FIFTEEN_MINUTES)
// The kms key to use for the destination bucket.
.kmsKey(destinationEncryptionKey)
// The storage class to use for the destination bucket.
.storageClass(StorageClass.INFREQUENT_ACCESS)
// Whether to replicate objects with SSE-KMS encryption.
.sseKmsEncryptedObjects(false)
// Whether to replicate modifications on replicas.
.replicaModifications(true)
// Whether to replicate delete markers.
// This property cannot be enabled if the replication rule has a tag filter.
.deleteMarkerReplication(false)
// The ID of the rule.
.id("full-settings-rule")
// The object filter for the rule.
.filter(Filter.builder()
// The prefix filter for the rule.
.prefix("prefix")
// The tag filter for the rule.
.tags(List.of(Tag.builder()
.key("tagKey")
.value("tagValue")
.build()))
.build())
.build()))
.build();
// Grant permissions to the replication role.
// This method is not required if you choose to use an auto-generated replication role or manually grant permissions.
sourceBucket.grantReplicationPermission(replicationRole, GrantReplicationPermissionProps.builder()
// Optional. Specify the KMS key to use for decrypting objects in the source bucket.
.sourceDecryptionKey(encryptionKey)
.destinations(List.of(GrantReplicationPermissionDestinationProps.builder().bucket(destinationBucket1).build(), GrantReplicationPermissionDestinationProps.builder().bucket(destinationBucket2).encryptionKey(destinationEncryptionKey).build()))
.build());
IBucket destinationBucket1;
IBucket destinationBucket2;
IRole replicationRole;
IKey encryptionKey;
IKey destinationEncryptionKey;
var sourceBucket = new Bucket(this, "SourceBucket", new BucketProps {
// Versioning must be enabled on both the source and destination bucket
Versioned = true,
// Optional. Specify the KMS key to use for encrypts objects in the source bucket.
EncryptionKey = encryptionKey,
// Optional. If not specified, a new role will be created.
ReplicationRole = replicationRole,
ReplicationRules = new [] { new ReplicationRule {
// The destination bucket for the replication rule.
Destination = destinationBucket1,
// The priority of the rule.
// Amazon S3 will attempt to replicate objects according to all replication rules.
// However, if there are two or more rules with the same destination bucket, then objects will be replicated according to the rule with the highest priority.
// The higher the number, the higher the priority.
// It is essential to specify priority explicitly when the replication configuration has multiple rules.
Priority = 1
}, new ReplicationRule {
Destination = destinationBucket2,
Priority = 2,
// Whether to specify S3 Replication Time Control (S3 RTC).
// S3 RTC replicates most objects that you upload to Amazon S3 in seconds,
// and 99.99 percent of those objects within specified time.
ReplicationTimeControl = ReplicationTimeValue.FIFTEEN_MINUTES,
// Whether to enable replication metrics about S3 RTC.
// If set, metrics will be output to indicate whether replication by S3 RTC took longer than the configured time.
Metrics = ReplicationTimeValue.FIFTEEN_MINUTES,
// The kms key to use for the destination bucket.
KmsKey = destinationEncryptionKey,
// The storage class to use for the destination bucket.
StorageClass = StorageClass.INFREQUENT_ACCESS,
// Whether to replicate objects with SSE-KMS encryption.
SseKmsEncryptedObjects = false,
// Whether to replicate modifications on replicas.
ReplicaModifications = true,
// Whether to replicate delete markers.
// This property cannot be enabled if the replication rule has a tag filter.
DeleteMarkerReplication = false,
// The ID of the rule.
Id = "full-settings-rule",
// The object filter for the rule.
Filter = new Filter {
// The prefix filter for the rule.
Prefix = "prefix",
// The tag filter for the rule.
Tags = new [] { new Tag {
Key = "tagKey",
Value = "tagValue"
} }
}
} }
});
// Grant permissions to the replication role.
// This method is not required if you choose to use an auto-generated replication role or manually grant permissions.
sourceBucket.GrantReplicationPermission(replicationRole, new GrantReplicationPermissionProps {
// Optional. Specify the KMS key to use for decrypting objects in the source bucket.
SourceDecryptionKey = encryptionKey,
Destinations = new [] { new GrantReplicationPermissionDestinationProps { Bucket = destinationBucket1 }, new GrantReplicationPermissionDestinationProps { Bucket = destinationBucket2, EncryptionKey = destinationEncryptionKey } }
});
var destinationBucket1 IBucket
var destinationBucket2 IBucket
var replicationRole IRole
var encryptionKey IKey
var destinationEncryptionKey IKey
sourceBucket := s3.NewBucket(this, jsii.String("SourceBucket"), &BucketProps{
// Versioning must be enabled on both the source and destination bucket
Versioned: jsii.Boolean(true),
// Optional. Specify the KMS key to use for encrypts objects in the source bucket.
EncryptionKey: EncryptionKey,
// Optional. If not specified, a new role will be created.
ReplicationRole: ReplicationRole,
ReplicationRules: []ReplicationRule{
&ReplicationRule{
// The destination bucket for the replication rule.
Destination: destinationBucket1,
// The priority of the rule.
// Amazon S3 will attempt to replicate objects according to all replication rules.
// However, if there are two or more rules with the same destination bucket, then objects will be replicated according to the rule with the highest priority.
// The higher the number, the higher the priority.
// It is essential to specify priority explicitly when the replication configuration has multiple rules.
Priority: jsii.Number(1),
},
&ReplicationRule{
Destination: destinationBucket2,
Priority: jsii.Number(2),
// Whether to specify S3 Replication Time Control (S3 RTC).
// S3 RTC replicates most objects that you upload to Amazon S3 in seconds,
// and 99.99 percent of those objects within specified time.
ReplicationTimeControl: s3.ReplicationTimeValue_FIFTEEN_MINUTES(),
// Whether to enable replication metrics about S3 RTC.
// If set, metrics will be output to indicate whether replication by S3 RTC took longer than the configured time.
Metrics: s3.ReplicationTimeValue_FIFTEEN_MINUTES(),
// The kms key to use for the destination bucket.
KmsKey: destinationEncryptionKey,
// The storage class to use for the destination bucket.
StorageClass: s3.StorageClass_INFREQUENT_ACCESS(),
// Whether to replicate objects with SSE-KMS encryption.
SseKmsEncryptedObjects: jsii.Boolean(false),
// Whether to replicate modifications on replicas.
ReplicaModifications: jsii.Boolean(true),
// Whether to replicate delete markers.
// This property cannot be enabled if the replication rule has a tag filter.
DeleteMarkerReplication: jsii.Boolean(false),
// The ID of the rule.
Id: jsii.String("full-settings-rule"),
// The object filter for the rule.
Filter: &Filter{
// The prefix filter for the rule.
Prefix: jsii.String("prefix"),
// The tag filter for the rule.
Tags: []Tag{
&Tag{
Key: jsii.String("tagKey"),
Value: jsii.String("tagValue"),
},
},
},
},
},
})
// Grant permissions to the replication role.
// This method is not required if you choose to use an auto-generated replication role or manually grant permissions.
sourceBucket.GrantReplicationPermission(replicationRole, &GrantReplicationPermissionProps{
// Optional. Specify the KMS key to use for decrypting objects in the source bucket.
SourceDecryptionKey: encryptionKey,
Destinations: []GrantReplicationPermissionDestinationProps{
&GrantReplicationPermissionDestinationProps{
Bucket: destinationBucket1,
},
&GrantReplicationPermissionDestinationProps{
Bucket: destinationBucket2,
EncryptionKey: destinationEncryptionKey,
},
},
})
Cross Account Replication
You can also set a destination bucket from a different account as the replication destination.
Cross-account replication requires a bucket policy on the destination bucket. If the destination bucket is managed by CDK, use addReplicationPolicy() to add the required permissions.
// A bucket defined in a CDK stack in the destination account.
declare const destinationBucket: s3.Bucket;
// The account ID that owns the source bucket.
declare const sourceAccountId: string;
const sourceBucket = new s3.Bucket(this, 'SourceBucket', {
versioned: true,
replicationRules: [
{
destination: destinationBucket,
priority: 1,
// Change replica ownership to the account that owns the destination bucket.
accessControlTransition: true,
},
],
});
// Add the required permissions to the destination bucket policy.
if (sourceBucket.replicationRoleArn) {
destinationBucket.addReplicationPolicy(
sourceBucket.replicationRoleArn,
true,
sourceAccountId,
);
}
# A bucket defined in a CDK stack in the destination account.
# destination_bucket: s3.Bucket
# The account ID that owns the source bucket.
# source_account_id: str
source_bucket = s3.Bucket(self, "SourceBucket",
versioned=True,
replication_rules=[s3.ReplicationRule(
destination=destination_bucket,
priority=1,
# Change replica ownership to the account that owns the destination bucket.
access_control_transition=True
)
]
)
# Add the required permissions to the destination bucket policy.
if source_bucket.replication_role_arn:
destination_bucket.add_replication_policy(source_bucket.replication_role_arn, True, source_account_id)
// A bucket defined in a CDK stack in the destination account.
Bucket destinationBucket;
// The account ID that owns the source bucket.
String sourceAccountId;
Bucket sourceBucket = Bucket.Builder.create(this, "SourceBucket")
.versioned(true)
.replicationRules(List.of(ReplicationRule.builder()
.destination(destinationBucket)
.priority(1)
// Change replica ownership to the account that owns the destination bucket.
.accessControlTransition(true)
.build()))
.build();
// Add the required permissions to the destination bucket policy.
if (sourceBucket.getReplicationRoleArn()) {
destinationBucket.addReplicationPolicy(sourceBucket.getReplicationRoleArn(), true, sourceAccountId);
}
// A bucket defined in a CDK stack in the destination account.
Bucket destinationBucket;
// The account ID that owns the source bucket.
string sourceAccountId;
var sourceBucket = new Bucket(this, "SourceBucket", new BucketProps {
Versioned = true,
ReplicationRules = new [] { new ReplicationRule {
Destination = destinationBucket,
Priority = 1,
// Change replica ownership to the account that owns the destination bucket.
AccessControlTransition = true
} }
});
// Add the required permissions to the destination bucket policy.
if (sourceBucket.ReplicationRoleArn)
{
destinationBucket.AddReplicationPolicy(sourceBucket.ReplicationRoleArn, true, sourceAccountId);
}
// A bucket defined in a CDK stack in the destination account.
var destinationBucket Bucket
// The account ID that owns the source bucket.
var sourceAccountId string
sourceBucket := s3.NewBucket(this, jsii.String("SourceBucket"), &BucketProps{
Versioned: jsii.Boolean(true),
ReplicationRules: []ReplicationRule{
&ReplicationRule{
Destination: destinationBucket,
Priority: jsii.Number(1),
// Change replica ownership to the account that owns the destination bucket.
AccessControlTransition: jsii.Boolean(true),
},
},
})
// Add the required permissions to the destination bucket policy.
if sourceBucket.ReplicationRoleArn {
destinationBucket.AddReplicationPolicy(sourceBucket.ReplicationRoleArn, jsii.Boolean(true), sourceAccountId)
}
The account ID passed to addReplicationPolicy() is the source bucket owner's account ID. CDK uses the destination bucket construct's account for the replication configuration.
If the destination bucket uses ObjectOwnership.BUCKET_OWNER_ENFORCED, the destination bucket owner already owns all replicated objects and accessControlTransition is not required. The ownership override shown above is useful for ACL-enabled destination buckets.
When importing an existing cross-account destination into the source stack, use Bucket.fromBucketAttributes() and set its account attribute to the destination bucket owner's account ID. Bucket.fromBucketArn() and Bucket.fromBucketName() assume that the bucket belongs to the same account as the scope where it is imported. Referenced buckets cannot have their bucket policy modified by CDK, so configure the required bucket policy separately in the destination account.
In a cross-account scenario, you can use a KMS key to encrypt object replicas. The KMS key owner must grant the source bucket owner permission to use the key. AWS managed keys do not allow cross-account use and therefore cannot be used for cross-account replication.
For more information, see Changing the replica owner.
Mixins
S3 provides several mixins that can be applied to L1 and L2 constructs.
BucketAutoDeleteObjects
Automatically deletes all objects from a bucket when the bucket is removed from the stack or when the stack is deleted. Requires the bucket's removal policy to be set to DESTROY:
new s3.CfnBucket(this, 'Bucket')
.with(new s3.mixins.BucketAutoDeleteObjects());
s3.CfnBucket(self, "Bucket").with(s3.mixins.BucketAutoDeleteObjects())
new CfnBucket(this, "Bucket").with(new BucketAutoDeleteObjects());
new CfnBucket(this, "Bucket").With(new Mixins.BucketAutoDeleteObjects());
s3.NewCfnBucket(this, jsii.String("Bucket")).With(#error#.NewBucketAutoDeleteObjects())
BucketVersioning
Enables or suspends versioning on an S3 bucket:
new s3.CfnBucket(this, 'Bucket')
.with(new s3.mixins.BucketVersioning());
s3.CfnBucket(self, "Bucket").with(s3.mixins.BucketVersioning())
new CfnBucket(this, "Bucket").with(new BucketVersioning());
new CfnBucket(this, "Bucket").With(new Mixins.BucketVersioning());
s3.NewCfnBucket(this, jsii.String("Bucket")).With(#error#.NewBucketVersioning())
BucketBlockPublicAccess
Blocks public access on an S3 bucket. Defaults to blocking all public access:
new s3.CfnBucket(this, 'Bucket')
.with(new s3.mixins.BucketBlockPublicAccess());
s3.CfnBucket(self, "Bucket").with(s3.mixins.BucketBlockPublicAccess())
new CfnBucket(this, "Bucket").with(new BucketBlockPublicAccess());
new CfnBucket(this, "Bucket").With(new Mixins.BucketBlockPublicAccess());
s3.NewCfnBucket(this, jsii.String("Bucket")).With(#error#.NewBucketBlockPublicAccess())
BucketPolicyStatements
Adds IAM policy statements to a bucket policy:
new s3.CfnBucketPolicy(this, 'Policy', {
bucket: new s3.CfnBucket(this, 'Bucket').ref,
policyDocument: new iam.PolicyDocument(),
}).with(new s3.mixins.BucketPolicyStatements([
new iam.PolicyStatement({
actions: ['s3:GetObject'],
resources: ['*'],
principals: [new iam.AnyPrincipal()],
}),
]));
s3.CfnBucketPolicy(self, "Policy",
bucket=s3.CfnBucket(self, "Bucket").ref,
policy_document=iam.PolicyDocument()
).with(s3.mixins.BucketPolicyStatements([
iam.PolicyStatement(
actions=["s3:GetObject"],
resources=["*"],
principals=[iam.AnyPrincipal()]
)
]))
CfnBucketPolicy.Builder.create(this, "Policy")
.bucket(new CfnBucket(this, "Bucket").ref)
.policyDocument(new PolicyDocument())
.build().with(new BucketPolicyStatements(List.of(
PolicyStatement.Builder.create()
.actions(List.of("s3:GetObject"))
.resources(List.of("*"))
.principals(List.of(new AnyPrincipal()))
.build())));
new CfnBucketPolicy(this, "Policy", new CfnBucketPolicyProps {
Bucket = new CfnBucket(this, "Bucket").Ref,
PolicyDocument = new PolicyDocument()
}).With(new Mixins.BucketPolicyStatements(new [] {
new PolicyStatement(new PolicyStatementProps {
Actions = new [] { "s3:GetObject" },
Resources = new [] { "*" },
Principals = new [] { new AnyPrincipal() }
}) }));
s3.NewCfnBucketPolicy(this, jsii.String("Policy"), &CfnBucketPolicyProps{
Bucket: s3.NewCfnBucket(this, jsii.String("Bucket")).ref,
PolicyDocument: iam.NewPolicyDocument(),
}).With(#error#.NewBucketPolicyStatements([]PolicyStatement{
iam.NewPolicyStatement(&PolicyStatementProps{
Actions: []*string{
jsii.String("s3:GetObject"),
},
Resources: []*string{
jsii.String("*"),
},
Principals: []IPrincipal{
iam.NewAnyPrincipal(),
},
}),
}))
Types
| Name | Kind | Summary |
|---|---|---|
Bucket | Construct (L2) | An S3 bucket with associated policy objects. |
BucketBase | Construct (L2) | Represents an S3 Bucket. |
BucketPolicy | Construct (L2) | The bucket policy for an Amazon S3 bucket. |
CfnAccessGrant | Construct (L1) | The AWS::S3::AccessGrant resource creates an access grant that gives a grantee access to your S3 data. |
CfnAccessGrantsInstance | Construct (L1) | The AWS::S3::AccessGrantInstance resource creates an S3 Access Grants instance, which serves as a logical grouping for access grants. |
CfnAccessGrantsLocation | Construct (L1) | The AWS::S3::AccessGrantsLocation resource creates the S3 data location that you would like to register in your S3 Access Grants instance. |
CfnAccessPoint | Construct (L1) | The AWS::S3::AccessPoint resource is an Amazon S3 resource type that you can use to access buckets. |
CfnBucket | Construct (L1) | The AWS::S3::Bucket resource creates an Amazon S3 bucket in the same AWS Region where you create the AWS CloudFormation stack. |
CfnBucketPolicy | Construct (L1) | Applies an Amazon S3 bucket policy to an Amazon S3 bucket. |
CfnMultiRegionAccessPoint | Construct (L1) | The AWS::S3::MultiRegionAccessPoint resource creates an Amazon S3 Multi-Region Access Point. |
CfnMultiRegionAccessPointPolicy | Construct (L1) | Applies an Amazon S3 access policy to an Amazon S3 Multi-Region Access Point. |
CfnStorageLens | Construct (L1) | The AWS::S3::StorageLens resource creates an Amazon S3 Storage Lens configuration. |
CfnStorageLensGroup | Construct (L1) | The AWS::S3::StorageLensGroup resource creates an S3 Storage Lens group. |
BlockedEncryptionType | Class | Encryption types that can be blocked on an S3 bucket. |
BlockPublicAccess | Class | |
BlockPublicAccessOptions | Struct | |
BucketAccessControl | Enum | Default bucket access control types. |
BucketAttributes | Struct | A reference to a bucket outside this stack. |
BucketEncryption | Enum | What kind of server-side encryption to apply to this bucket. |
BucketGrants | Facade | Collection of grant methods for a Bucket. |
BucketMetrics | Struct | Specifies a metrics configuration for the CloudWatch request metrics from an Amazon S3 bucket. |
BucketNamespace | Enum | The namespace for the bucket name when using bucketNamePrefix. |
BucketNotificationDestinationConfig | Struct | Represents the properties of a notification destination. |
BucketNotificationDestinationType | Enum | Supported types of notification destinations. |
BucketPolicyProps | Struct | |
BucketProps | Struct | |
CfnAccessGrant.AccessGrantsLocationConfigurationProperty | Struct | The configuration options of the S3 Access Grants location. |
CfnAccessGrant.GranteeProperty | Struct | The user, group, or role to which you are granting access. |
CfnAccessGrantProps | Struct | Properties for defining a CfnAccessGrant. |
CfnAccessGrantsInstanceProps | Struct | Properties for defining a CfnAccessGrantsInstance. |
CfnAccessGrantsLocationProps | Struct | Properties for defining a CfnAccessGrantsLocation. |
CfnAccessPoint.PublicAccessBlockConfigurationProperty | Struct | The PublicAccessBlock configuration that you want to apply to this Amazon S3 bucket. |
CfnAccessPoint.VpcConfigurationProperty | Struct | The Virtual Private Cloud (VPC) configuration for this access point. |
CfnAccessPointProps | Struct | Properties for defining a CfnAccessPoint. |
CfnBucket.AbortIncompleteMultipartUploadProperty | Struct | Specifies the days since the initiation of an incomplete multipart upload that Amazon S3 will wait before permanently removing all parts of the upload. |
CfnBucket.AccelerateConfigurationProperty | Struct | Configures the transfer acceleration state for an Amazon S3 bucket. |
CfnBucket.AccessControlTranslationProperty | Struct | Specify this only in a cross-account scenario (where source and destination bucket owners are not the same), and you want to change replica ownership to the AWS account that owns the destination bucket. |
CfnBucket.AnalyticsConfigurationProperty | Struct | Specifies the configuration and any analyses for the analytics filter of an Amazon S3 bucket. |
CfnBucket.AnnotationTableConfigurationProperty | Struct | The annotation table configuration for an S3 Metadata configuration. |
CfnBucket.BlockedEncryptionTypesProperty | Struct | A bucket-level setting for Amazon S3 general purpose buckets used to prevent the upload of new objects encrypted with the specified server-side encryption type. |
CfnBucket.BucketEncryptionProperty | Struct | Specifies default encryption for a bucket using server-side encryption with Amazon S3-managed keys (SSE-S3), AWS KMS-managed keys (SSE-KMS), or dual-layer server-side encryption with KMS-managed keys (DSSE-KMS). |
CfnBucket.CorsConfigurationProperty | Struct | Describes the cross-origin access configuration for objects in an Amazon S3 bucket. |
CfnBucket.CorsRuleProperty | Struct | Specifies a cross-origin access rule for an Amazon S3 bucket. |
CfnBucket.DataExportProperty | Struct | Specifies how data related to the storage class analysis for an Amazon S3 bucket should be exported. |
CfnBucket.DefaultEventHoldProperty | Struct | |
CfnBucket.DefaultRetentionProperty | Struct | The container element for optionally specifying the default Object Lock retention settings for new objects placed in the specified bucket. |
CfnBucket.DeleteMarkerReplicationProperty | Struct | Specifies whether Amazon S3 replicates delete markers. |
CfnBucket.DestinationProperty | Struct | Specifies information about where to publish analysis or configuration results for an Amazon S3 bucket. |
CfnBucket.EncryptionConfigurationProperty | Struct | Specifies encryption-related information for an Amazon S3 bucket that is a destination for replicated objects. |
CfnBucket.EventBridgeConfigurationProperty | Struct | Amazon S3 can send events to Amazon EventBridge whenever certain events happen in your bucket, see Using EventBridge in the Amazon S3 User Guide . |
CfnBucket.FilterRuleProperty | Struct | Specifies the Amazon S3 object key name to filter on. |
CfnBucket.IntelligentTieringConfigurationProperty | Struct | Specifies the S3 Intelligent-Tiering configuration for an Amazon S3 bucket. |
CfnBucket.InventoryConfigurationProperty | Struct | Specifies the S3 Inventory configuration for an Amazon S3 bucket. |
CfnBucket.InventoryTableConfigurationProperty | Struct | The inventory table configuration for an S3 Metadata configuration. |
CfnBucket.JournalTableConfigurationProperty | Struct | The journal table configuration for an S3 Metadata configuration. |
CfnBucket.LambdaConfigurationProperty | Struct | Describes the AWS Lambda functions to invoke and the events for which to invoke them. |
CfnBucket.LifecycleConfigurationProperty | Struct | Specifies the lifecycle configuration for objects in an Amazon S3 bucket. |
CfnBucket.LoggingConfigurationProperty | Struct | Describes where logs are stored and the prefix that Amazon S3 assigns to all log object keys for a bucket. |
CfnBucket.MetadataConfigurationProperty | Struct | Creates a V2 Amazon S3 Metadata configuration of a general purpose bucket. |
CfnBucket.MetadataDestinationProperty | Struct | The destination information for the S3 Metadata configuration. |
CfnBucket.MetadataTableConfigurationProperty | Struct | > We recommend that you create your S3 Metadata configurations by using the V2 MetadataConfiguration resource type. We no longer recommend using the V1 MetadataTableConfiguration resource type. > > If you created your S3 Metadata configuration before July 15, 2025, we recommend that you delete and re-create your configuration by using the MetadataConfiguration resource type so that you can expire journal table records and create a live inventory table. |
CfnBucket.MetadataTableEncryptionConfigurationProperty | Struct | The encryption settings for an S3 Metadata journal table or inventory table configuration. |
CfnBucket.MetricsConfigurationProperty | Struct | Specifies a metrics configuration for the CloudWatch request metrics (specified by the metrics configuration ID) from an Amazon S3 bucket. |
CfnBucket.MetricsProperty | Struct | A container specifying replication metrics-related settings enabling replication metrics and events. |
CfnBucket.NoncurrentVersionExpirationProperty | Struct | Specifies when noncurrent object versions expire. |
CfnBucket.NoncurrentVersionTransitionProperty | Struct | Container for the transition rule that describes when noncurrent objects transition to the STANDARD_IA , ONEZONE_IA , INTELLIGENT_TIERING , GLACIER_IR , GLACIER , or DEEP_ARCHIVE storage class. |
CfnBucket.NotificationConfigurationProperty | Struct | Describes the notification configuration for an Amazon S3 bucket. |
CfnBucket.NotificationFilterProperty | Struct | Specifies object key name filtering rules. |
CfnBucket.ObjectLockConfigurationProperty | Struct | Places an Object Lock configuration on the specified bucket. |
CfnBucket.ObjectLockRuleProperty | Struct | Specifies the Object Lock rule for the specified object. |
CfnBucket.OwnershipControlsProperty | Struct | Specifies the container element for Object Ownership rules. |
CfnBucket.OwnershipControlsRuleProperty | Struct | Specifies an Object Ownership rule. |
CfnBucket.PartitionedPrefixProperty | Struct | Amazon S3 keys for log objects are partitioned in the following format:. |
CfnBucket.PublicAccessBlockConfigurationProperty | Struct | The PublicAccessBlock configuration that you want to apply to this Amazon S3 bucket. |
CfnBucket.QueueConfigurationProperty | Struct | Specifies the configuration for publishing messages to an Amazon Simple Queue Service (Amazon SQS) queue when Amazon S3 detects specified events. |
CfnBucket.RecordExpirationProperty | Struct | The journal table record expiration settings for a journal table in an S3 Metadata configuration. |
CfnBucket.RedirectAllRequestsToProperty | Struct | Specifies the redirect behavior of all requests to a website endpoint of an Amazon S3 bucket. |
CfnBucket.RedirectRuleProperty | Struct | Specifies how requests are redirected. |
CfnBucket.ReplicaModificationsProperty | Struct | A filter that you can specify for selection for modifications on replicas. |
CfnBucket.ReplicationConfigurationProperty | Struct | A container for replication rules. |
CfnBucket.ReplicationDestinationProperty | Struct | A container for information about the replication destination and its configurations including enabling the S3 Replication Time Control (S3 RTC). |
CfnBucket.ReplicationRuleAndOperatorProperty | Struct | A container for specifying rule filters. |
CfnBucket.ReplicationRuleFilterProperty | Struct | A filter that identifies the subset of objects to which the replication rule applies. |
CfnBucket.ReplicationRuleProperty | Struct | Specifies which Amazon S3 objects to replicate and where to store the replicas. |
CfnBucket.ReplicationTimeProperty | Struct | A container specifying S3 Replication Time Control (S3 RTC) related information, including whether S3 RTC is enabled and the time when all objects and operations on objects must be replicated. |
CfnBucket.ReplicationTimeValueProperty | Struct | A container specifying the time value for S3 Replication Time Control (S3 RTC) and replication metrics EventThreshold . |
CfnBucket.RoutingRuleConditionProperty | Struct | A container for describing a condition that must be met for the specified redirect to apply. |
CfnBucket.RoutingRuleProperty | Struct | Specifies the redirect behavior and when a redirect is applied. |
CfnBucket.RuleProperty | Struct | Specifies lifecycle rules for an Amazon S3 bucket. |
CfnBucket.S3KeyFilterProperty | Struct | A container for object key name prefix and suffix filtering rules. |
CfnBucket.S3TablesDestinationProperty | Struct | The destination information for a V1 S3 Metadata configuration. |
CfnBucket.ServerSideEncryptionByDefaultProperty | Struct | Describes the default server-side encryption to apply to new objects in the bucket. |
CfnBucket.ServerSideEncryptionRuleProperty | Struct | Specifies the default server-side encryption configuration. |
CfnBucket.SourceSelectionCriteriaProperty | Struct | A container that describes additional filters for identifying the source objects that you want to replicate. |
CfnBucket.SseKmsEncryptedObjectsProperty | Struct | A container for filter information for the selection of S3 objects encrypted with AWS KMS. |
CfnBucket.StorageClassAnalysisProperty | Struct | Specifies data related to access patterns to be collected and made available to analyze the tradeoffs between different storage classes for an Amazon S3 bucket. |
CfnBucket.TagFilterProperty | Struct | Specifies tags to use to identify a subset of objects for an Amazon S3 bucket. |
CfnBucket.TargetObjectKeyFormatProperty | Struct | Amazon S3 key format for log objects. |
CfnBucket.TieringProperty | Struct | The S3 Intelligent-Tiering storage class is designed to optimize storage costs by automatically moving data to the most cost-effective storage access tier, without additional operational overhead. |
CfnBucket.TopicConfigurationProperty | Struct | A container for specifying the configuration for publication of messages to an Amazon Simple Notification Service (Amazon SNS) topic when Amazon S3 detects specified events. |
CfnBucket.TransitionProperty | Struct | Specifies when an object transitions to a specified storage class. |
CfnBucket.VersioningConfigurationProperty | Struct | Describes the versioning state of an Amazon S3 bucket. |
CfnBucket.WebsiteConfigurationProperty | Struct | Specifies website configuration parameters for an Amazon S3 bucket. |
CfnBucketPolicyProps | Struct | Properties for defining a CfnBucketPolicy. |
CfnBucketProps | Struct | Properties for defining a CfnBucket. |
CfnMultiRegionAccessPoint.PublicAccessBlockConfigurationProperty | Struct | The PublicAccessBlock configuration that you want to apply to this Amazon S3 Multi-Region Access Point. |
CfnMultiRegionAccessPoint.RegionProperty | Struct | A bucket associated with a specific Region when creating Multi-Region Access Points. |
CfnMultiRegionAccessPointPolicy.PolicyStatusProperty | Struct | The container element for a bucket's policy status. |
CfnMultiRegionAccessPointPolicyProps | Struct | Properties for defining a CfnMultiRegionAccessPointPolicy. |
CfnMultiRegionAccessPointProps | Struct | Properties for defining a CfnMultiRegionAccessPoint. |
CfnStorageLens.AccountLevelProperty | Struct | This resource contains the details of the account-level metrics for Amazon S3 Storage Lens. |
CfnStorageLens.ActivityMetricsProperty | Struct | This resource enables Amazon S3 Storage Lens activity metrics. |
CfnStorageLens.AdvancedCostOptimizationMetricsProperty | Struct | This resource enables Amazon S3 Storage Lens advanced cost optimization metrics. |
CfnStorageLens.AdvancedDataProtectionMetricsProperty | Struct | This resource enables Amazon S3 Storage Lens advanced data protection metrics. |
CfnStorageLens.AdvancedPerformanceMetricsProperty | Struct | A property for S3 Storage Lens advanced performance metrics. |
CfnStorageLens.AwsOrgProperty | Struct | This resource contains the details of the AWS Organization for Amazon S3 Storage Lens. |
CfnStorageLens.BucketLevelProperty | Struct | A property for the bucket-level storage metrics for Amazon S3 Storage Lens. |
CfnStorageLens.BucketsAndRegionsProperty | Struct | This resource contains the details of the buckets and Regions for the Amazon S3 Storage Lens configuration. |
CfnStorageLens.CloudWatchMetricsProperty | Struct | This resource enables the Amazon CloudWatch publishing option for Amazon S3 Storage Lens metrics. |
CfnStorageLens.DataExportProperty | Struct | This resource contains the details of the Amazon S3 Storage Lens metrics export. |
CfnStorageLens.DetailedStatusCodesMetricsProperty | Struct | This resource enables Amazon S3 Storage Lens detailed status code metrics. |
CfnStorageLens.EncryptionProperty | Struct | This resource contains the type of server-side encryption used to encrypt an Amazon S3 Storage Lens metrics export. |
CfnStorageLens.PrefixLevelProperty | Struct | This resource contains the details of the prefix-level of the Amazon S3 Storage Lens. |
CfnStorageLens.PrefixLevelStorageMetricsProperty | Struct | This resource contains the details of the prefix-level storage metrics for Amazon S3 Storage Lens. |
CfnStorageLens.S3BucketDestinationProperty | Struct | This resource contains the details of the bucket where the Amazon S3 Storage Lens metrics export will be placed. |
CfnStorageLens.SelectionCriteriaProperty | Struct | This resource contains the details of the Amazon S3 Storage Lens selection criteria. |
CfnStorageLens.SSEKMSProperty | Struct | Specifies the use of server-side encryption using an AWS Key Management Service key (SSE-KMS) to encrypt the delivered S3 Storage Lens metrics export file. |
CfnStorageLens.StorageLensConfigurationProperty | Struct | This is the property of the Amazon S3 Storage Lens configuration. |
CfnStorageLens.StorageLensExpandedPrefixesDataExportProperty | Struct | This resource specifies the properties of your S3 Storage Lens Expanded Prefixes metrics export. |
CfnStorageLens.StorageLensGroupLevelProperty | Struct | This resource determines the scope of Storage Lens group data that is displayed in the Storage Lens dashboard. |
CfnStorageLens.StorageLensGroupSelectionCriteriaProperty | Struct | This resource indicates which Storage Lens group ARNs to include or exclude in the Storage Lens group aggregation. |
CfnStorageLens.StorageLensTableDestinationProperty | Struct | This resource configures your S3 Storage Lens reports to export to read-only S3 table buckets. |
CfnStorageLensGroup.AndProperty | Struct | This resource is a logical operator that allows multiple filter conditions to be joined for more complex comparisons of Storage Lens group data. |
CfnStorageLensGroup.FilterProperty | Struct | This resource sets the criteria for the Storage Lens group data that is displayed. |
CfnStorageLensGroup.MatchObjectAgeProperty | Struct | This resource contains DaysGreaterThan and DaysLessThan to define the object age range (minimum and maximum number of days). |
CfnStorageLensGroup.MatchObjectSizeProperty | Struct | This resource filters objects that match the specified object size range. |
CfnStorageLensGroup.OrProperty | Struct | This resource contains the Or logical operator, which allows multiple filter conditions to be joined for more complex comparisons of Storage Lens group data. |
CfnStorageLensGroupProps | Struct | Properties for defining a CfnStorageLensGroup. |
CfnStorageLensProps | Struct | Properties for defining a CfnStorageLens. |
CorsRule | Struct | Specifies a cross-origin access rule for an Amazon S3 bucket. |
EventType | Enum | Notification event types. |
Filter | Struct | A filter that identifies the subset of objects to which the replication rule applies. |
GrantReplicationPermissionDestinationProps | Struct | The properties for the destination bucket for granting replication permission. |
GrantReplicationPermissionProps | Struct | The properties for the destination bucket for granting replication permission. |
HttpMethods | Enum | All http request methods. |
IBucket | Interface | |
IBucketNotificationDestination | Interface | Implemented by constructs that can be used as bucket notification destinations. |
IntelligentTieringConfiguration | Struct | The intelligent tiering configuration. |
Inventory | Struct | Specifies the inventory configuration of an S3 Bucket. |
InventoryDestination | Struct | The destination of the inventory. |
InventoryFormat | Enum | All supported inventory list formats. |
InventoryFrequency | Enum | All supported inventory frequencies. |
InventoryObjectVersion | Enum | Inventory version support. |
LifecycleRule | Struct | Declaration of a Life cycle rule. |
Location | Struct | An interface that represents the location of a specific object in an S3 Bucket. |
NoncurrentVersionTransition | Struct | Describes when noncurrent versions transition to a specified storage class. |
NotificationKeyFilter | Struct | |
ObjectLockMode | Enum | Modes in which S3 Object Lock retention can be configured. |
ObjectLockRetention | Class | The default retention settings for an S3 Object Lock configuration. |
ObjectOwnership | Enum | The ObjectOwnership of the bucket. |
OnCloudTrailBucketEventOptions | Struct | Options for the onCloudTrailPutObject method. |
PartitionDateSource | Enum | The date source for the partitioned prefix. |
RedirectProtocol | Enum | All http request methods. |
RedirectTarget | Struct | Specifies a redirect behavior of all requests to a website endpoint of a bucket. |
ReplaceKey | Class | |
ReplicationRule | Struct | Specifies which Amazon S3 objects to replicate and where to store the replicas. |
ReplicationTimeValue | Class | The replication time value used for S3 Replication Time Control (S3 RTC). |
RoutingRule | Struct | Rule that define when a redirect is applied and the redirect behavior. |
RoutingRuleCondition | Struct | |
StorageClass | Class | Storage class to move an object to. |
Tag | Struct | Tag. |
TargetObjectKeyFormat | Class | The key format for the log object. |
TransferAccelerationUrlOptions | Struct | Options for creating a Transfer Acceleration URL. |
Transition | Struct | Describes when an object transitions to a specified storage class. |
TransitionDefaultMinimumObjectSize | Enum | The transition default minimum object size for lifecycle. |
VirtualHostedStyleUrlOptions | Struct | Options for creating Virtual-Hosted style URL. |