DEV Community

Danny Steenman for AWS Community Builders

Posted on • Originally published at towardsthecloud.com on

How to set up an Amazon S3 Bucket using AWS CDK

This how-to guide will explain what is required to create an Amazon S3 bucket in AWS CDK TypeScript. The example code that is provided comes with all steps required to run and deploy the AWS CDK code in AWS Cloud.

First, you’ll learn how to install AWS CDK and configure an IAM profile for your AWS account so that it enables you to deploy the code from the AWS CLI. Once you’ve learned how to synthesize the Amazon S3 Bucket construct, you can then proceed to deploy it and after you’re done you can clean up the resources using AWS CDK destroy.

Here are the steps that allow you to set up and configure an Amazon S3 Bucket using AWS CDK:

Table of Contents

How to set up an Amazon S3 Bucket Using AWS CDK TypeScript

Before we start building the Amazon S3 Bucket construct, you’re required to have done the following prerequisites before you can run AWS CDK code in TypeScript.

  • Install AWS CDK and TypeScript NPM packages
  • Install the AWS CLI and configure an AWS profile
  • Create an AWS CDK TypeScript project

If you’ve already done this, you can proceed to step 4.

1. Install AWS CDK

Use the NPM package manager in your terminal to install AWS CDK and TypeScript globally on your system:

➜ npm install -g aws-cdk typescript

added 180 packages, and audited 181 packages in 7s
found 0 vulnerabilities
~ took 7s
Enter fullscreen mode Exit fullscreen mode

Once you’ve installed AWS CDK you can validate that you’re running on the latest version by running the following command in the terminal:

➜ cdk version

2.23.0 (build 50444aa)
Enter fullscreen mode Exit fullscreen mode

2. Install AWS CLI and configure an AWS profile

The AWS CLI is a command line tool that allows you to interact with AWS services in your terminal. Depending on if you’re running Linux, macOS, or Windows the installation goes like this:

# macOS install method:
brew install awscli

# Windows install method:
wget https://awscli.amazonaws.com/AWSCLIV2.msi
msiexec.exe /i https://awscli.amazonaws.com/AWSCLIV2.msi

# Linux (Ubuntu) install method:
sudo apt install awscli
Enter fullscreen mode Exit fullscreen mode

In order to access your AWS account with the AWS CLI, you first need to configure an AWS Profile. There are 2 ways of configuring a profile:

  • Access and secret key credentials from an IAM user
  • AWS Single Sign-on (SSO) user

In this article, I’ll briefly explain how to configure the first method so that you can proceed more quickly to set up the Amazon S3 Bucket in AWS CDK.

If you wish to set up the AWS profile more securely, then I’d suggest you read and apply the steps described in setting up AWS CLI with AWS Single Sign-On (SSO).

In order to configure the AWS CLI with your IAM user’s access and secret key credentials, you need to login to the AWS Console. Go to IAM > Users, select your IAM user and click on the Security credentials tab to create an access and secret key.

Then configure the AWS profile on the AWS CLI as follows:

➜ aws configure
AWS Access Key ID [None]: <insert_access_key>
AWS Secret Access Key [None]: <insert_secret_key>
Default region name [None]: <insert_aws_region>
Default output format [json]: json
Enter fullscreen mode Exit fullscreen mode

Your was credentials are storen in ~/.aws/credentials and as you can validate that that you AWS profile is working by running the command:

➜ aws sts get-caller-identity
{
    "UserId": "AIDA5BRFSNF24CDMD7FNY",
    "Account": "012345678901",
    "Arn": "arn:aws:iam::012345678901:user/test-user"
}
Enter fullscreen mode Exit fullscreen mode

3. Create a new AWS CDK TypeScript Project

Now that we’ve configured our profile and installed the packages, it’s time to create an AWS CDK TypeScript project where you’re going to build the Amazon S3 Bucket construct.

You can generate a new AWS CDK TypeScript project by running the following command in an empty directory:

➜ cdk init sample-app --language=typescript

Applying project template sample-app for typescript
# Welcome to your CDK TypeScript project!
You should explore the contents of this project. It demonstrates a CDK app with an instance of a stack (`CdkProjectStack`)
which contains an Amazon SQS queue that is subscribed to an Amazon SNS topic.
The `cdk.json` file tells the CDK Toolkit how to execute your app.
## Useful commands
 * `npm run build`   compile typescript to js
 * `npm run watch`   watch for changes and compile
 * `npm run test`    perform the jest unit tests
 * `cdk deploy`      deploy this stack to your default AWS account/region
 * `cdk diff`        compare deployed stack with current state
 * `cdk synth`       emits the synthesized CloudFormation template
Initializing a new git repository...
Executing npm install...
✅ All done!
Enter fullscreen mode Exit fullscreen mode

4. Create an Amazon S3 Bucket construct in AWS CDK

The following example defines an Amazon S3 bucket in a stack by creating an instance of the Bucket class which is an L2 construct.

import * as cdk from 'aws-cdk-lib';
import * as iam from 'aws-cdk-lib/aws-iam';
import * as kms from 'aws-cdk-lib/aws-kms';
import * as s3 from 'aws-cdk-lib/aws-s3';
import { Construct } from 'constructs';

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

    const s3Bucket = new s3.Bucket(this, 'exampleBucket', {
      objectOwnership: s3.ObjectOwnership.BUCKET_OWNER_ENFORCED,
      blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
      encryptionKey: new kms.Key(this, 's3BucketKMSKey'),
    });

    s3Bucket.grantRead(new iam.AccountRootPrincipal());
  }
}

const app = new cdk.App();
new S3BucketStack(app, 'S3BucketStack');
app.synth();
Enter fullscreen mode Exit fullscreen mode

You can create an S3 bucket in a simple oneliner, but I’ve chosen to add 3 important properties that help secure the S3 Bucket. Let’s go over these properties:

objectOwnership – Allows you to disable access control lists (ACLs) and take ownership of every object in your bucket. This will simplify the way you manage access to objects that are stored in your Amazon S3 bucket.

blockPublicAccess – Permissions on new objects that are stored in the S3 bucket are private by default and don’t allow public access.

encryptionKey – Allows you to use a customer managed KMS key to encrypt the S3 bucket objects in rest.

At last, we use the s3Bucket.grantRead method to give the AWS account owner read access to the specified exampleBucket.

5. Synthesize your Amazon S3 Bucket in AWS CDK

The Amazon S3 Bucket construct has been created in a stack. Now you can generate the CloudFormation template by running AWS CDK Synthesize:

➜ cdk synth

Resources:
  exampleBucketB33BA2C4:
    Type: AWS::S3::Bucket
    Properties:
      BucketEncryption:
        ServerSideEncryptionConfiguration:
          - ServerSideEncryptionByDefault:
              KMSMasterKeyID:
                Fn::GetAtt:
                  - s3BucketKMSKey2D51E7FB
                  - Arn
              SSEAlgorithm: aws:kms
      OwnershipControls:
        Rules:
          - ObjectOwnership: BucketOwnerEnforced
      PublicAccessBlockConfiguration:
        BlockPublicAcls: true
        BlockPublicPolicy: true
        IgnorePublicAcls: true
        RestrictPublicBuckets: true
    UpdateReplacePolicy: Retain
    DeletionPolicy: Retain
    Metadata:
      aws:cdk:path: S3BucketStack/exampleBucket/Resource
....
....
Enter fullscreen mode Exit fullscreen mode

As you can see in the command output above, it will print the stack output in YAML format in stdout.

You can ignore that, the generated template is stored in JSON format in the cdk.out folder of your AWS CDK project.

.
├── cdk.json
├── cdk.out
│ ├── cdk.out
│ ├── manifest.json
│ ├── S3BucketStack.assets.json
│ ├── S3BucketStack.template.json
│ └── tree.json
├── main.ts
├── package-lock.json
├── package.json
├── README.md
└── tsconfig.json
Enter fullscreen mode Exit fullscreen mode



  1. Deploy your Amazon S3 Bucket to AWS Cloud using AWS CDK

To deploy the S3 bucket to your AWS account, run the deploy command:

➜ cdk deploy

✨ Synthesis time: 16.66s

This deployment will make potentially sensitive changes according to your current security approval level (--require-approval broadening).
Please confirm you intend to make the following modifications:

IAM Statement Changes
┌───┬───────────────────────────────────────────┬────────┬───────────────────────────────────────────┬────────────────────────────────────────────┬───────────┐
│ │ Resource │ Effect │ Action │ Principal │ Condition │
├───┼───────────────────────────────────────────┼────────┼───────────────────────────────────────────┼────────────────────────────────────────────┼───────────┤
│ + │ ${exampleBucket.Arn} │ Allow │ s3:GetBucket* │ AWS:arn:${AWS::Partition}:iam::${AWS::Acco │ │
│ │ ${exampleBucket.Arn}/* │ │ s3:GetObject* │ untId}:root │ │
│ │ │ │ s3:List* │ │ │
├───┼───────────────────────────────────────────┼────────┼───────────────────────────────────────────┼────────────────────────────────────────────┼───────────┤
│ + │ ${s3BucketKMSKey.Arn} │ Allow │ kms:* │ AWS:arn:${AWS::Partition}:iam::${AWS::Acco │ │
│ │ │ │ │ untId}:root │ │
│ + │ ${s3BucketKMSKey.Arn} │ Allow │ kms:Decrypt │ AWS:arn:${AWS::Partition}:iam::${AWS::Acco │ │
│ │ │ │ kms:DescribeKey │ untId}:root │ │
└───┴───────────────────────────────────────────┴────────┴───────────────────────────────────────────┴────────────────────────────────────────────┴───────────┘
(NOTE: There may be security-related changes not in this list. See https://github.com/aws/aws-cdk/issues/1299)

Do you wish to deploy these changes (y/n)? y
S3BucketStack: deploying...
[0%] start: Publishing a26790c45fb73467eeeccc9ae55cffac604567459906d91c75237364eaf42df9:current_account-current_region
[100%] success: Published a26790c45fb73467eeeccc9ae55cffac604567459906d91c75237364eaf42df9:current_account-current_region
S3BucketStack: creating CloudFormation changeset...

✅ S3BucketStack

✨ Deployment time: 167.98s

Stack ARN:
arn:aws:cloudformation:eu-central-1:896653224309:stack/S3BucketStack/109c23d0-0697-11ed-8de7-06dec59fa0d6

✨ Total time: 184.64s

Enter fullscreen mode Exit fullscreen mode



  1. Destroy Your Amazon S3 Bucket Using AWS CDK

To clean up the AWS resources that were created for this project, run the destroy command:

➜ cdk destroy
Are you sure you want to delete: S3BucketStack (y/n)? y
S3BucketStack: destroying...

✅ S3BucketStack: destroyed

Enter fullscreen mode Exit fullscreen mode




Conclusion

You were able to successfully set up an Amazon S3 Bucket using AWS CDK TypeScript. The additional S3 Bucket properties allow you to further secure access and encrypt the objects that are stored on the bucket.

Source

Top comments (0)