or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

access-control-security.mdbucket-management.mdindex.mdlifecycle-storage.mdnotifications-events.md
tile.json

tessl/npm-aws-cdk--aws-s3

AWS CDK Construct Library for Amazon S3 - provides high-level constructs for creating and configuring S3 buckets and related resources

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@aws-cdk/aws-s3@1.204.x

To install, run

npx @tessl/cli install tessl/npm-aws-cdk--aws-s3@1.204.0

index.mddocs/

AWS CDK S3 Construct Library

The 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.

Package Information

  • Package Name: @aws-cdk/aws-s3
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install @aws-cdk/aws-s3
  • CDK Version: v1 (End-of-Support as of 2023-06-01)

Core Imports

import * 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');

Basic Usage

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' }
    );
  }
}

Architecture

The AWS CDK S3 library is built around several key components:

  • Core Bucket Classes: Bucket (concrete implementation) and BucketBase (abstract base) provide the main S3 bucket constructs
  • Interface Abstraction: IBucket interface enables working with both created and imported buckets consistently
  • Configuration Objects: Comprehensive props interfaces (BucketProps, LifecycleRule, etc.) for fine-grained bucket configuration
  • Security Controls: BlockPublicAccess utility and BucketPolicy construct for access control
  • Integration Points: Built-in support for IAM, KMS, CloudWatch Events, and Lambda integrations
  • CloudFormation Resources: Low-level L1 constructs (CfnBucket) for direct CloudFormation resource control

Capabilities

Bucket Management

Core 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;
}

Bucket Management

Lifecycle and Storage Management

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;
}

Lifecycle and Storage

Notifications and Events

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;
}

Notifications and Events

Access Control and Security

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'
}

Access Control and Security

CloudTrail Integration

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;

URL Generation

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;

Common Types

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;
}