AWS CDK Construct Library for Amazon S3 - provides high-level constructs for creating and configuring S3 buckets and related resources
npx @tessl/cli install tessl/npm-aws-cdk--aws-s3@1.204.0The AWS CDK S3 Construct Library provides high-level constructs for creating and configuring Amazon S3 buckets and related resources. It offers comprehensive bucket management with built-in security best practices, lifecycle policies, notifications, access control, and seamless integration with other AWS services through the CDK framework.
npm install @aws-cdk/aws-s3import * as s3 from '@aws-cdk/aws-s3';
import { Bucket, BucketProps, IBucket } from '@aws-cdk/aws-s3';For CommonJS:
const s3 = require('@aws-cdk/aws-s3');
const { Bucket } = require('@aws-cdk/aws-s3');import * as s3 from '@aws-cdk/aws-s3';
import * as s3n from '@aws-cdk/aws-s3-notifications';
import * as cdk from '@aws-cdk/core';
import * as lambda from '@aws-cdk/aws-lambda';
import * as sns from '@aws-cdk/aws-sns';
export class MyS3Stack extends cdk.Stack {
constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
// Create a basic S3 bucket
const bucket = new s3.Bucket(this, 'MyBucket');
// Create an encrypted bucket with lifecycle rules
const encryptedBucket = new s3.Bucket(this, 'MyEncryptedBucket', {
encryption: s3.BucketEncryption.KMS,
versioned: true,
lifecycleRules: [{
id: 'DeleteOldVersions',
noncurrentVersionExpiration: cdk.Duration.days(30),
}],
// Block all public access by default
blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
});
// Example Lambda function for demonstration
const myLambdaFunction = new lambda.Function(this, 'MyFunction', {
runtime: lambda.Runtime.NODEJS_14_X,
handler: 'index.handler',
code: lambda.Code.fromInline('exports.handler = async () => { console.log("Hello from Lambda!"); };')
});
// Example SNS topic for notifications
const myTopic = new sns.Topic(this, 'MyTopic');
// Grant permissions to other resources
bucket.grantReadWrite(myLambdaFunction);
// Add event notifications
bucket.addEventNotification(
s3.EventType.OBJECT_CREATED,
new s3n.SnsDestination(myTopic),
{ prefix: 'uploads/', suffix: '.jpg' }
);
}
}The AWS CDK S3 library is built around several key components:
Bucket (concrete implementation) and BucketBase (abstract base) provide the main S3 bucket constructsIBucket interface enables working with both created and imported buckets consistentlyBucketProps, LifecycleRule, etc.) for fine-grained bucket configurationBlockPublicAccess utility and BucketPolicy construct for access controlCfnBucket) for direct CloudFormation resource controlCore bucket creation, configuration, and lifecycle management functionality. Supports encryption, versioning, lifecycle policies, and comprehensive security controls.
class Bucket extends BucketBase {
constructor(scope: Construct, id: string, props?: BucketProps);
static fromBucketArn(scope: Construct, id: string, bucketArn: string): IBucket;
static fromBucketName(scope: Construct, id: string, bucketName: string): IBucket;
static fromBucketAttributes(scope: Construct, id: string, attrs: BucketAttributes): IBucket;
}
interface IBucket extends IResource {
readonly bucketArn: string;
readonly bucketName: string;
readonly bucketWebsiteUrl: string;
readonly bucketDomainName: string;
readonly bucketRegionalDomainName: string;
readonly bucketDualStackDomainName: string;
readonly encryptionKey?: kms.IKey;
addEventNotification(event: EventType, dest: IBucketNotificationDestination, ...filters: NotificationKeyFilter[]): void;
addToResourcePolicy(permission: iam.PolicyStatement): iam.AddToResourcePolicyResult;
addCorsRule(rule: CorsRule): void;
addLifecycleRule(rule: LifecycleRule): void;
addMetric(metric: BucketMetrics): void;
addInventory(inventory: Inventory): void;
arnForObjects(keyPattern: string): string;
onCloudTrailEvent(id: string, options?: OnCloudTrailBucketEventOptions): events.Rule;
onCloudTrailPutObject(id: string, options?: OnCloudTrailBucketEventOptions): events.Rule;
onCloudTrailWriteObject(id: string, options?: OnCloudTrailBucketEventOptions): events.Rule;
urlForObject(key?: string): string;
virtualHostedUrlForObject(key?: string, options?: VirtualHostedStyleUrlOptions): string;
transferAccelerationUrlForObject(key?: string, options?: TransferAccelerationUrlOptions): string;
s3UrlForObject(key?: string): string;
grantRead(identity: iam.IGrantable, objectsKeyPattern?: any): iam.Grant;
grantWrite(identity: iam.IGrantable, objectsKeyPattern?: any): iam.Grant;
grantReadWrite(identity: iam.IGrantable, objectsKeyPattern?: any): iam.Grant;
}Advanced storage management features including lifecycle policies, intelligent tiering, storage class transitions, and object expiration rules.
interface LifecycleRule {
id?: string;
enabled?: boolean;
prefix?: string;
expiration?: Duration;
noncurrentVersionExpiration?: Duration;
transitions?: Transition[];
noncurrentVersionTransitions?: NoncurrentVersionTransition[];
abortIncompleteMultipartUploadAfter?: Duration;
tagFilters?: {[tag: string]: any};
}
interface Transition {
storageClass: StorageClass;
transitionAfter: Duration;
transitionDate?: Date;
}
class StorageClass {
static readonly STANDARD: StorageClass;
static readonly REDUCED_REDUNDANCY: StorageClass;
static readonly STANDARD_INFREQUENT_ACCESS: StorageClass;
static readonly ONEZONE_INFREQUENT_ACCESS: StorageClass;
static readonly INTELLIGENT_TIERING: StorageClass;
static readonly GLACIER: StorageClass;
static readonly DEEP_ARCHIVE: StorageClass;
}S3 event notification system supporting SNS, SQS, and Lambda destinations with flexible filtering options and EventBridge integration.
enum EventType {
OBJECT_CREATED = 's3:ObjectCreated:*',
OBJECT_CREATED_PUT = 's3:ObjectCreated:Put',
OBJECT_CREATED_POST = 's3:ObjectCreated:Post',
OBJECT_CREATED_COPY = 's3:ObjectCreated:Copy',
OBJECT_CREATED_COMPLETE_MULTIPART_UPLOAD = 's3:ObjectCreated:CompleteMultipartUpload',
OBJECT_REMOVED = 's3:ObjectRemoved:*',
OBJECT_REMOVED_DELETE = 's3:ObjectRemoved:Delete',
OBJECT_REMOVED_DELETE_MARKER_CREATED = 's3:ObjectRemoved:DeleteMarkerCreated',
REDUCED_REDUNDANCY_LOST_OBJECT = 's3:ReducedRedundancyLostObject',
REPLICATION_OPERATION_FAILED_REPLICATION = 's3:Replication:OperationFailedReplication',
REPLICATION_OPERATION_MISSED_THRESHOLD = 's3:Replication:OperationMissedThreshold',
REPLICATION_OPERATION_REPLICATED_AFTER_THRESHOLD = 's3:Replication:OperationReplicatedAfterThreshold',
REPLICATION_OPERATION_NOT_TRACKED = 's3:Replication:OperationNotTracked'
}
interface IBucketNotificationDestination {
bind(scope: Construct, bucket: IBucket): BucketNotificationDestinationConfig;
}
interface NotificationKeyFilter {
prefix?: string;
suffix?: string;
}Comprehensive security features including bucket policies, public access controls, SSL enforcement, and IAM integration with grant methods.
class BlockPublicAccess {
static readonly BLOCK_ALL: BlockPublicAccess;
static readonly BLOCK_ACLS: BlockPublicAccess;
readonly blockPublicAcls?: boolean;
readonly blockPublicPolicy?: boolean;
readonly ignorePublicAcls?: boolean;
readonly restrictPublicBuckets?: boolean;
constructor(options: BlockPublicAccessOptions);
}
class BucketPolicy extends Resource {
constructor(scope: Construct, id: string, props: BucketPolicyProps);
readonly document: iam.PolicyDocument;
}
enum BucketEncryption {
UNENCRYPTED = 'NONE',
KMS_MANAGED = 'MANAGED',
S3_MANAGED = 'S3MANAGED',
KMS = 'KMS'
}CloudWatch event rules that monitor S3 API calls via CloudTrail for auditing, compliance, and automated workflows. Enables real-time responses to S3 operations.
interface OnCloudTrailBucketEventOptions extends events.OnEventOptions {
readonly paths?: string[];
}
// Methods in IBucket interface:
onCloudTrailEvent(id: string, options?: OnCloudTrailBucketEventOptions): events.Rule;
onCloudTrailPutObject(id: string, options?: OnCloudTrailBucketEventOptions): events.Rule;
onCloudTrailWriteObject(id: string, options?: OnCloudTrailBucketEventOptions): events.Rule;Generate various URL formats for S3 objects including standard HTTPS, virtual hosted-style, transfer acceleration, and S3 protocol URLs.
interface VirtualHostedStyleUrlOptions {
readonly regional?: boolean;
}
interface TransferAccelerationUrlOptions {
readonly dualStack?: boolean;
}
// Methods in IBucket interface:
urlForObject(key?: string): string;
virtualHostedUrlForObject(key?: string, options?: VirtualHostedStyleUrlOptions): string;
transferAccelerationUrlForObject(key?: string, options?: TransferAccelerationUrlOptions): string;
s3UrlForObject(key?: string): string;
arnForObjects(keyPattern: string): string;interface BucketProps {
bucketName?: string;
versioned?: boolean;
encryption?: BucketEncryption;
encryptionKey?: kms.IKey;
bucketKeyEnabled?: boolean;
blockPublicAccess?: BlockPublicAccess;
publicReadAccess?: boolean;
websiteIndexDocument?: string;
websiteErrorDocument?: string;
websiteRedirect?: RedirectTarget;
lifecycleRules?: LifecycleRule[];
cors?: CorsRule[];
serverAccessLogsPrefix?: string;
serverAccessLogsBucket?: IBucket;
inventories?: Inventory[];
metrics?: BucketMetrics[];
transferAcceleration?: boolean;
enforceSSL?: boolean;
eventBridgeEnabled?: boolean;
removalPolicy?: RemovalPolicy;
autoDeleteObjects?: boolean;
notificationsHandlerRole?: iam.IRole;
}
interface BucketAttributes {
bucketArn?: string;
bucketName?: string;
bucketDomainName?: string;
bucketWebsiteUrl?: string;
bucketRegionalDomainName?: string;
bucketDualStackDomainName?: string;
encryptionKey?: kms.IKey;
isWebsite?: boolean;
region?: string;
}
interface Location {
bucketName: string;
objectKey: string;
objectVersion?: string;
}
interface RedirectTarget {
hostName?: string;
httpRedirectCode?: string;
protocol?: RedirectProtocol;
replaceKey?: ReplaceKey;
}
interface CorsRule {
allowedMethods: HttpMethods[];
allowedOrigins: string[];
allowedHeaders?: string[];
exposedHeaders?: string[];
id?: string;
maxAge?: number;
}
enum HttpMethods {
GET = 'GET',
PUT = 'PUT',
HEAD = 'HEAD',
POST = 'POST',
DELETE = 'DELETE'
}
interface Inventory {
inventoryId: string;
destination: InventoryDestination;
enabled?: boolean;
format?: InventoryFormat;
frequency?: InventoryFrequency;
includeObjectVersions?: InventoryObjectVersion;
objectsPrefix?: string;
optionalFields?: string[];
}
interface BucketMetrics {
id: string;
prefix?: string;
tagFilters?: {[tag: string]: any};
}
interface BucketNotificationDestinationConfig {
type: BucketNotificationDestinationType;
arn: string;
dependencies?: IDependable[];
}
enum BucketNotificationDestinationType {
LAMBDA,
QUEUE,
TOPIC
}
interface BlockPublicAccessOptions {
blockPublicAcls?: boolean;
blockPublicPolicy?: boolean;
ignorePublicAcls?: boolean;
restrictPublicBuckets?: boolean;
}
interface BucketPolicyProps {
bucket: IBucket;
removalPolicy?: RemovalPolicy;
}