S3 Bucket Example in AWS CDK - Complete Guide

avatar

Borislav Hadzhiev

Mon May 10 20213 min read

Creating an S3 Bucket in AWS CDK #

In this article we are going to cover some of the most common properties we use to create and configure an S3 bucket in AWS CDK.

In order to create an S3 bucket in CDK, we have to instantiate and configure the Bucket class.

The code for this article is available on GitHub

Note that all of the props we're going to pass to the bucket in the second example are optional. You could create an S3 bucket in CDK, with a simple one-liner:

lib/cdk-starter-stack.ts
import * as s3 from '@aws-cdk/aws-s3'; import * as cdk from '@aws-cdk/core'; export class CdkStarterStack extends cdk.Stack { constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { super(scope, id, props); const s3Bucket = new s3.Bucket(this, 's3-bucket') } }

I'll post the complete code snippet of configuring an S3 bucket in CDK and then we'll go over the details.

lib/cdk-starter-stack.ts
import * as s3 from '@aws-cdk/aws-s3'; import * as cdk from '@aws-cdk/core'; import * as iam from '@aws-cdk/aws-iam'; export class CdkStarterStack extends cdk.Stack { constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { super(scope, id, props); // ๐Ÿ‘‡ create bucket const s3Bucket = new s3.Bucket(this, 's3-bucket', { // bucketName: 'my-bucket', removalPolicy: cdk.RemovalPolicy.DESTROY, autoDeleteObjects: true, versioned: false, publicReadAccess: false, encryption: s3.BucketEncryption.S3_MANAGED, cors: [ { allowedMethods: [ s3.HttpMethods.GET, s3.HttpMethods.POST, s3.HttpMethods.PUT, ], allowedOrigins: ['http://localhost:3000'], allowedHeaders: ['*'], }, ], lifecycleRules: [ { abortIncompleteMultipartUploadAfter: cdk.Duration.days(90), expiration: cdk.Duration.days(365), transitions: [ { storageClass: s3.StorageClass.INFREQUENT_ACCESS, transitionAfter: cdk.Duration.days(30), }, ], }, ], }); // ๐Ÿ‘‡ grant access to bucket s3Bucket.grantRead(new iam.AccountRootPrincipal()); } }

Let's go over what we did in the code snippet.

  1. we created a bucket by instantiating the Bucket class

  2. the props we've passed to the constructor are:

NameDescription
bucketNamein our case it's commented out. It's not recommended to hard code a name for the bucket, because they must be globally unique. If we leave the prop out, CloudFormation auto generates a name
removalPolicyspecify what should happen to the bucket if the CDK stack is deleted. We've set the removal policy to DESTROY (bucket gets deleted). By default, the bucket is retained in an orphaned state.
autoDeleteObjectsautomatically empty the bucket's contents when our stack is deleted, which enables us to delete the bucket.
versionedwether versioning should be enabled for the S3 bucket
publicReadAccesswhether all objects in the bucket should be publicly accessible
encryptionoptionally specify the type of server-side encryption for the stored objects
corsallows HTTP requests from other domains, for example when making request from website.com to amazonaws.com to upload an object to the bucket
lifecycleRulesallows us to transition infrequently accessed into different storage categories in an attempt to save money
  1. lastly, we have used the grantRead method on the bucket instance to grant read access to the owner of the account, in which the stack was created.

The service-to-service interaction methods, that are exposed by CDK constructs are the main selling point of the service. To grant write permissions on an s3 bucket to a lambda function is as simple as:

s3Bucket.grantWrite(lambda);
The code for this article is available on GitHub
The autoDeleteObjects prop, which empties a bucket before deleting it, on stack deletion, is a one-liner, which creates a CloudFormation custom resource for us. The custom resource is a lambda function that takes care of emptying the bucket for us.

All these abstractions, provided by CDK make our code much easier to read and understand (than CloudFormation).

To deploy the bucket, you'd have to execute the deploy command:

shell
npx cdk deploy

If we take a look at the CloudFormation management console, after the deployment, we can see that CDK has provisioned a total of 6 resources for us:

cloudformation resources

Clean up #

To delete the stack and the provisioned resources, execute the destroy command:

shell
npx cdk destroy

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee