Using AWS CDK to Create an AWS S3 Bucket

Introduction

In my previous post, I introduced AWS S3 and showed how to set it up using the AWS CLI and NodeJS. In this post, I’ll show you how to use the AWS CDK to manage your AWS resources - specifically, how to create an S3 bucket.

The AWS Cloud Development Kit (AWS CDK) is an open-source framework for defining Infrastructure as Code (IaC). Instead of writing long, complex YAML or JSON configuration files (like CloudFormation), CDK lets you use familiar programming languages like TypeScript, Python, Java, C#, or Go to manage your AWS resources.

Why use AWS CDK?

  • Use languages you already know: You can use loops, conditions, variables, and Object-Oriented Programming (OOP) to define your infrastructure.
  • Great IDE support: You get features like autocomplete, error checking as you type, and built-in documentation.
  • Reusable code: You can easily package your infrastructure into libraries to share across different projects.

Prerequisites

First, you need an AWS account. You will also need your AWS Access Key ID and AWS Secret Access Key with permissions to use AWS S3.

If you have a new AWS account, you can create a user by going to IAM > Users > Create user. Once created, go to the user's details, click the Security credentials tab, find the Access key section, and click Create access key.


Next, run the following command to configure your credentials so the AWS CDK can use them:

aws configure


Step-by-Step Guide

First, install the CDK package using NPM:

npm install -g aws-cdk


Create a new AWS CDK project:

cdk init app --language typescript


Once the project is created, pay attention to these files:

  • lib/aws-cdk-stack.ts: An empty starting stack.
  • bin/aws-cdk.ts: The entry point that executes the stacks defined in your lib directory.


Create a new file named lib/aws-s3-stack.ts to define your S3 bucket:

import * as cdk from "aws-cdk-lib";
import { Construct } from "constructs";
import * as s3 from "aws-cdk-lib/aws-s3";
import { randomBytes } from "crypto";

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

    const myBucket = new s3.Bucket(this, "MyFirstBucket", {
      bucketName: this.createBucketName("bucket-name-test"),
      removalPolicy: cdk.RemovalPolicy.DESTROY,
      autoDeleteObjects: true,
      versioned: true,
      encryption: s3.BucketEncryption.S3_MANAGED,
    });

    new cdk.CfnOutput(this, "BucketName", {
      value: myBucket.bucketName,
    });
  }

  createBucketName(prefix: string): string {
    const cleanPrefix = prefix.toLowerCase().replace(/[^a-z0-t0-9]/g, "-");
    const suffix = randomBytes(4).toString("hex");
    return `${cleanPrefix}-${suffix}`;
  }
}

Explanation of Settings:

  • bucketName: Bucket names must be globally unique. I’ve included a createBucketName function that adds a random hex suffix to your chosen name.
  • removalPolicy: Setting this to DESTROY ensures the bucket is deleted when the Stack is deleted.
  • autoDeleteObjects: Automatically deletes files inside the bucket before deleting the bucket itself.
  • versioned: Keeps a history of old versions of your files.
  • encryption: Configures data encryption.


Next, update bin/aws-cdk.ts (or your entry file) to use your stacks:

#!/usr/bin/env node
import * as cdk from "aws-cdk-lib/core";
import { AwsCdkStack } from "../lib/aws-cdk-stack";
import { AwsS3Stack } from "../lib/aws-s3-stack";

const app = new cdk.App();
new AwsCdkStack(app, "AwsCdkStack", {});
new AwsS3Stack(app, "AwsS3Stack");

Note: You can name these stacks whatever you like; these names are used for deploying and destroying resources later.


Now, run the bootstrap command:

cdk bootstrap

This sets up a "CDKToolkit" stack on AWS CloudFormation. You only need to do this once per project/region.


To see what changes will be made before you actually deploy:

cdk diff


To deploy your resources to AWS, use one of the following commands:

cdk deploy # Use this if you only have one stack
cdk deploy {stackName} # Use this to deploy a specific stack
cdk deploy Dev-* # You can use wildcards
cdk deploy --all # Deploy every stack in the project
cdk deploy --all --require-approval never # Deploy all and skip manual approval prompts


Once the execution is finished, you can check your stacks in AWS CloudFormation.



Your S3 Bucket has also been successfully created.


When you no longer need the resources, you can delete them to avoid costs:

cdk destroy
cdk destroy {stackName}


See you in the next article!

See more articles here.

Comments

Popular posts from this blog

All practice series

Deploying a NodeJS Server on Google Kubernetes Engine

Setting up Kubernetes Dashboard with Kind

Using Kafka with Docker and NodeJS

Monitoring with cAdvisor, Prometheus and Grafana on Docker

Kubernetes Practice Series

Kubernetes Deployment for Zero Downtime

Practicing with Google Cloud Platform - Google Kubernetes Engine to deploy nginx

NodeJS Practice Series

Helm for beginer - Deploy nginx to Google Kubernetes Engine