Danh mụcThẻBài viết

admin

I'm a Full-stack developer

Thẻ

Linked List
Data Structure
Chat GPT
Design Pattern
Microservices
API
AWS CDK
ReactJS
AWS Lightsail
Flutter Mobile
Create S3 Bucket with AWS CDK
Ngày đăng: 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/
Đề xuất

JOI - API schema validation
admin12/06/2023

JOI - API schema validation
Data validation is one of topics that I am interesting. I always review my code after developed features or fixed bugs. There are many places where need to validate data, it is really terrible. Some cases, we need to validate data input because ensure the data into API, it will not make any problems to crash system.
How to integrate ChatGPT-3.5 Turbo into Node.js
admin10/01/2024

How to integrate ChatGPT-3.5 Turbo into Node.js
Step-by-Step Guide to Incorporating ChatGPT-3.5 Turbo into Node.js for Basic ReactJS Applications
Mới nhất

Writing a Data Transformation Pipeline Using Go
admin20/03/2024

Writing a Data Transformation Pipeline Using Go
In this article, I will show how to implement data processing using the Go programing language with a simple tutorial.
Difference Between Stack and Queue
admin07/04/2024

Difference Between Stack and Queue
In the fundamental data structure, besides the linked list, the stack and queue are also used widely in computer science and programming.
Part 1: How to deploy Ghost Blog on AWS using Lightsail
admin17/06/2023

Part 1: How to deploy Ghost Blog on AWS using Lightsail
In this article, I want to introduce about how to deploy Ghost Blog on AWS using Lightsail.
Đ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
Góp ý
Họ & Tên
Số điện thoại
Email
Nội dung
Tải ứng dụng
hotline

copyright © 2023 - AGAPIFA

Privacy
Term
About