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

RESTful API - How to design?
admin09/06/2023

RESTful API - How to design?
In this article, I will describe the useful points of designing a good API.
Part 3: Upgrade Latest Ghost Ver On AWS Lightsail
admin17/06/2023

Part 3: Upgrade Latest Ghost Ver On AWS Lightsail
You are a beginner with Ghost CMS, Bitanami, AWS Lightsail and don't know much about the documentation yet. So, in this article, I introduce step by step to upgrade Ghost CMS to the latest version.
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.
Mới nhất

Create S3 Bucket with AWS CDK
admin09/06/2023

Create S3 Bucket with AWS CDK
In this article, I introduce Amazon CDK and how to write AWS infrastructure-as-code using TypeScript. We will do it step by step.
TypeScript Design Pattern - Builder
admin07/08/2023

TypeScript Design Pattern - Builder
TypeScript Design Pattern - Builder
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.
Đ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