CategoryTagArticle

admin

I'm a Full-stack developer

Tag

Linked List
Data Structure
Chat GPT
Design Pattern
Microservices
API
AWS CDK
ReactJS
AWS Lightsail
Flutter Mobile
Create S3 Bucket with AWS CDK
Published date: 09/06/2023

In this article, I introduce Amazon CDK and how to write AWS infrastructure-as-code using TypeScript. We will do it step by step.


What is AWS CDK (Cloud Development Kit)?


AWS Cloud Development Kit (AWS CDK) accelerates cloud development using common programming languages to model your applications.


Setup


Step 1: Open command/terminal or PowerShell window

Step 2: Check node is installed or not. (If not installed, please visit the link to download some settings)

npm --version


Step 3: Check AWS CLI is installed or not

aws --version


Step 4: Install the AWS CDK CLI.

Use the npm command below to install the AWS CDK CLI.

npm install -g aws-cdk


Step 5: Verify AWS CDK is installed

cdk


Step 6: Create a CDK project

mkdir agapifa
cd agapifa


Step 7: Create the package.json

{
  "name": "agapifa",
  "version": "1.0.0",
  "description": "",
  "scripts": {
    "build": "npx tsc",
    "start": "npm run build -w",
    "cdk": "cdk",
    "diff": "npx aws-cdk diff",
    "deploy": "npx aws-cdk deploy",
    "destroy": "npx aws-cdk destroy",
    "lint": "eslint .",
    "lint:fix": "eslint --fix",
    "format": "prettier --write './**/*.{js,jsx,ts,tsx,css,md,json}' --config ./.prettierrc"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@trivago/prettier-plugin-sort-imports": "^4.0.0",
    "@types/node": "^18.13.0",
    "@typescript-eslint/eslint-plugin": "^5.51.0",
    "aws-cdk": "^2.73.0",
    "eslint": "^8.34.0",
    "eslint-config-prettier": "^8.6.0",
    "eslint-config-standard-with-typescript": "^34.0.0",
    "eslint-plugin-import": "^2.27.5",
    "eslint-plugin-prettier": "^4.2.1",
    "prettier": "^2.8.4",
    "ts-node": "^10.9.1",
    "typescript": "^4.9.5"
  },
  "dependencies": {
    "aws-cdk-lib": "^2.73.0",
    "constructs": "^10.1.306",
    "eslint-plugin-n": "^15.6.1",
    "eslint-plugin-promise": "^6.1.1",
    "source-map-support": "^0.5.21"
  }
}


Step 8: Create tsconfig.json

{
  "compilerOptions": {
    "noImplicitAny": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es2017",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "commonjs",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "baseUrl": "./",
    "rootDir": "./",
    "outDir": "./dist",
    "strictPropertyInitialization": false,
    "paths": {
      "@/*": ["src/*"]
    }
  },
  "include": ["**/*.ts"],
  "exclude": ["node_modules", "**/node_modules/*", "cdk.out"]
}


Step 9: Create cdk.json

{
  "app": "npx ts-node --prefer-ts-exts lib/index.ts",
  "context": {
    "@aws-cdk/core:newStyleStackSynthesis": "true",
    "@aws-cdk/core:bootstrapQualifier": "hnb659fds"
  }
}


Step 10: Code. (Create a directory tree like this)

Step 11: Add code to the file lib/index.ts

#!/usr/bin/env node
import { App } from 'aws-cdk-lib';
import { Construct } from 'constructs';

import apiStack from './stacks/api-stack';

class AgapifaApp extends Construct {
  constructor(scope: App, id: string) {
    super(scope, id);

    // API Stack
    new apiStack(this, `${id}-ApiStack`, {
      stackName: `${id}-ApiStack`,
    });
  }
}

const app = new App();

new AgapifaApp(app, 'Agapifa');


Step 12: Add the below content in lib/stacks/api-stack.ts

import { Stack, StackProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';

import S3Resource from '../../lib/resources/s3';

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

    new S3Resource(this, `${id}-S3`, {}).setupBucket('images').setupPolicies().build();
  }
}

export default ApiStack;


Step 13: Add content to lib/resources/s3/index.ts

import { Stack, StackProps, aws_iam as iam, aws_s3 as s3 } from 'aws-cdk-lib';

class S3Resource {
  private _s3Bucket: s3.Bucket;
  private _scope: Stack;
  private _scopeId: string;

  constructor(scope: Stack, id: string, props: StackProps) {
    this._scope = scope;
    this._scopeId = id;
  }

  setupBucket(bucketName: string) {
    this._s3Bucket = new s3.Bucket(this._scope, `${this._scopeId}-${bucketName}`, {
      bucketName: `${this._scopeId}-${bucketName}`.toLocaleLowerCase(),
      accessControl: s3.BucketAccessControl.BUCKET_OWNER_FULL_CONTROL,
      blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
      encryption: s3.BucketEncryption.S3_MANAGED,
    });

    return this;
  }

  setupPolicies() {
    this._s3Bucket.addToResourcePolicy(
      new iam.PolicyStatement({
        actions: ['*'],
        principals: [new iam.AnyPrincipal()],
        resources: [this._s3Bucket.bucketArn, this._s3Bucket.arnForObjects('*')],
      }),
    );

    return this;
  }

  build() {
    return this._s3Bucket;
  }
}

export default S3Resource;


Step 14: Build the AWS CDK application

yarn build


Step 15: Deploy the AWS CDK application

*** You need to bootstrap the AWS CDK application before you can deploy it to AWS

cdk bootstrap  --profile agapifa


Once you've installed it, you can continue with the deployment of the AWS CDK application.

cdk deploy --profile agapifa


Step 16: Check on the console

  • CloudFormation

  • S3

Summary


In this tutorial, you learned how to install the AWS CDK, set up and initialize an AWS CDK project, assemble it into a CloudFormation template, and deploy to AWS Cloud. If you want to remove the newly created stack from your AWS account, run the following command

cdk destroy --profile agapifa


Good luck with your installation!!!


Next: CREATE COGNITO USER POOL WITH AWS CDK


--------------------------------

Reference documents:


  1. https://aws.amazon.com/cdk/
Recommend

How to secure your API gateway
admin17/04/2024

How to secure your API gateway
In this blog, I will cover the 6 methods that technology leaders need to incorporate to secure and protect APIs.
TypeScript Design Pattern - Prototype
admin07/08/2023

TypeScript Design Pattern - Prototype
The prototype pattern is one of the Creational pattern groups. The responsibility is to create a new object through clone the existing object instead of using the new key. The new object is the same as the original object, and we can change its property does not impact the original object.
Microservice in a Monorepo
admin22/06/2023

Microservice in a Monorepo
Microservice in a Monorepo
Newest

How to secure your API gateway
admin17/04/2024

How to secure your API gateway
In this blog, I will cover the 6 methods that technology leaders need to incorporate to secure and protect APIs.
TypeScript Design Pattern - Bridge
admin08/08/2023

TypeScript Design Pattern - Bridge
Decouple an abstraction from its implementation so that the two can vary independently.
Next.js 14 App Router Localization with next-intl
admin07/07/2024

Next.js 14 App Router Localization with next-intl
In this article, I will illustrate how to implement next-intl localization in a Next.js 14 application
Đinh Thành Công Blog

My website, where I write blogs on a variety of topics and where I have some experiments with new technologies.

hotlinelinkedinskypezalofacebook
DMCA.com Protection Status
Feedback
Name
Phone number
Email
Content
Download app
hotline

copyright © 2023 - AGAPIFA

Privacy
Term
About