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

Design Patterns
admin07/08/2023

Design Patterns
The design pattern does not be a specific programming language. Almost programming languages might apply design patterns that to resolve a problem repeat.
Form validator in Flutter with EzValidator
admin04/01/2024

Form validator in Flutter with EzValidator
When I am working on Flutter with form. For ensuring data integrity, and handling user input errors. I want to show an error message below each TextField, Dropdown, Switch, ... if the user does not input or wrong input. The EzValidator help me to resolve this.
Part 4: How to use Redux Toolkit in React
admin18/06/2023

Part 4: How to use Redux Toolkit in React
In this article, I will explain Redux and delve into Redux Toolkit. a collection of tools that simplify using Redux. These tools help make Redux less daunting and easier to use.
Mới nhất

TypeScript Design Pattern - Proxy
admin11/08/2023

TypeScript Design Pattern - Proxy
Provide a surrogate or placeholder for another object to control access to it.
Part 5: Creating a Tag List Page on Ghost CMS
admin17/06/2023

Part 5: Creating a Tag List Page on Ghost CMS
In this article, I will show you how to create a Tag list page using the Casper theme.
NodeJS Verify and Decode Cognito JWT Tokens
admin12/06/2023

NodeJS Verify and Decode Cognito JWT Tokens
In this article, I will show you how to verify and decode the Cognito JWT Tokens token.
Đ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