This blog will teach us how to create an S3 bucket using CDK. AWS S3 (simple storage service) is a durable, petabyte-scale, and affordable cloud object storage. S3 buckets are containers for your data. Before storing any data in S3, we must create a bucket. I have written a blog on how to create an S3 bucket using python and AWS CLI. This blog will teach you how to do it using CDK.

S3 Bucket using CDK

The code below creates an S3 bucket. We do not need to pass any parameters to the S3 construct, and it will create an S3 bucket with all default values.

import {RemovalPolicy, Stack, StackProps} from 'aws-cdk-lib';
import {Construct} from 'constructs';
import * as s3 from 'aws-cdk-lib/aws-s3';

export class AwsS3Stack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);

    new s3.Bucket(this, "SimpleBucketFromCDK");

  }
}

In this code, we are just calling the S3 construct. When we deploy our stack, we can see that the S3 bucket has been created in AWS.

S3 bucket using CDK
S3 bucket using CDK

Giving S3 bucket name

When creating an S3 bucket, we can also set the name of our choice to an S3 bucket. This name should follow S3 bucket naming rules and should be unique.

// previous code

new s3.Bucket(this, "BucketFromCDK", {
      bucketName: "test-bucket-from-cdk-12",
    });

In this code, we pass `bucketName` to a value of our choice. Let us deploy our stack.

Create S3 bucket with custom name
Create an S3 bucket with a custom name

It worked! We have a bucket with a name that we passed.

Setting Up Bucket policies using CDK

By default, all buckets created in S3 are private. Therefore, users will not be able to upload or read files from the bucket. We can set these permissions when we create an S3 bucket.

import {Stack, StackProps} from 'aws-cdk-lib';
import {Construct} from 'constructs';
import * as s3 from 'aws-cdk-lib/aws-s3';

export class AwsS3Stack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);

    // ... previous code

    new s3.Bucket(this, "BucketWithPublicReadAccess", {
      accessControl: s3.BucketAccessControl.PUBLIC_READ
    })


  }
}

In code, we are passing `accessControl` param. It accepts BucketAccessControl enum. As we set up the PUBLIC_READ property for this bucket, everyone will be able to read files from this bucket.

BucketAccessControl enum has the below values.

  • PRIVATE
  • PUBLIC_READ
  • PUBLIC_READ_WRITE
  • AUTHENTICATED_READ
  • LOG_DELIVERY_WRITE
  • BUCKET_OWNER_READ
  • BUCKET_OWNER_FULL_CONTROL
  • AWS_EXEC_READ

If we want to set the PUBLIC_READ policy for the bucket, there is another more straightforward way. We can set `publicReadAccess` to true.

new s3.Bucket(this, "BucketWithPublicReadAccess", {
      // accessControl: s3.BucketAccessControl.PUBLIC_READ,
      publicReadAccess: true  //same as setting s3.BucketAccessControl.PUBLIC_READ
    })

Deleting S3 Bucket on CDK destroy

Now let us clean up our mess by running cdk destroy.

CDK destroy result
CDK destroy result

We can see that our stack has been successfully deleted. Let us check if it has deleted our buckets or not.

Ohh! our buckets are not yet deleted. Why so? Once the stack is deleted, shouldn’t it also delete all resources belonging to that stack?

Well, you are right. In most cases, once the stack is deleted, resources are deleted with it. But for a few resources, there is execution. CDK does not want us to lose any data we may have stored in the S3 bucket. Hence even after we run cdk destroy and the stack is deleted, our S3 buckets are not been deleted.

If we are sure that we do not want those buckets for later use, we can change this behavior. Let us go through the below code.

import {RemovalPolicy, Stack, StackProps} from 'aws-cdk-lib';
import {Construct} from 'constructs';
import * as s3 from 'aws-cdk-lib/aws-s3';

export class AwsS3Stack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);

    new s3.Bucket(this, "BucketFromCDK", {
      bucketName: "test-bucket-from-cdk-12",
      removalPolicy: RemovalPolicy.DESTROY
    });


  }
}

We are passing `removalPolicy` param. It accepts RemovalPolicy enum when has been imported from aws-cdk-lib. The default removal policy is RETAIN for S3 buckets. When we change that to DESTROY, our S3 bucket should be deleted once we delete the stack.

S3 construct parameters

The below table shows the most common parameters accepted by the S3 CDK construct. There are a few parameters that we have not discussed here. Let me know if you want to explain how those parameters work.

NameTypeDescriptionDefault Value
accessControlBucketAccessControl enumSets Access Control List (ACL) policy for the bucketPRIVATE
bucketNamestringName of the bucket
encryptionBucketEncryption EnumSets which type of server-side encryption should be applied to bucket UNENCRYPTED
lifecycleRulesLifecycleRule []Sets up lifecycle rules for objects in an S3 bucket No rules
publicReadAccessbooleanSets public read access for objects in an s3 bucketfalse
removalPolicyRemovalPolicy enumDecides on what happens to bucket when stack is deletedRETAIN
versionedbooleansets if versioning should be enabled for s3 bucket or notfalse

Conclusion

So we have created S3 buckets using CDK and learned about different ways to configure that bucket. I hope you have found this useful. See you in the next blog.

Share with your friends

Similar Posts

Leave a Reply

Your email address will not be published.