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:
Step-by-Step Guide
First, install the CDK package using NPM:
Create a new AWS CDK project:
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:
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:
Note: You can name these stacks whatever you like; these names are used for deploying and destroying resources later.
Now, run the bootstrap command:
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:
To deploy your resources to AWS, use one of the following commands:
When you no longer need the resources, you can delete them to avoid costs:
See you in the next article!
Comments
Post a Comment