Skip to main content

Command Palette

Search for a command to run...

Triển khai ứng dụng serverless trên AWS

Updated
5 min read
Triển khai ứng dụng serverless trên AWS

Mô hình

Tạo resource Cognito

Truy cập vào AWS Management Console:

  • Tìm và chọn Cognito

Trong giao diện Cognito:

  • Chọn Create user pool

Ở Step 1 Configure sign-in experience:

  • Cognito user pool sign-in options: User name và Email

Ở Step 2 Configure security requirements:

  • Password policy mode: Cognito default

  • Multi-factor authentication: No MFA

  • Self-service account recovery: Enable self-service account recovery - Recommended

  • Delivery method for user account recovery messages: Email only

Ở Step 3 Configure sign-up experience:

  • Self-registration: Enable self-registration

  • Automatically send: Allow Cognito to automatically send messages to verify and confirm

  • Attributes to verify: Send email message, verify email address

Ở Step 4 Configure message delivery:

  • Email: Send email with Cognito

  • FROM email address: no-reply@verificationemail.com

Ở Step 5 Integrate your app:

  • User pool name: KMA_cognito

  • Chọn Use the Cognito Hosted UI

  • App type: Public client

  • App client name: KMA_client

  • Client secret: Don’t generate a client secret

Kết quả sau khi tạo:

Thực hiện kết nối ứng dụng với cognito

Thực hiện pull code từ github: https://github.com/HoangPhan10/aws-serverless.git

Mở file .env.local và thay đổi 2 thông số AWS_USER_POOLS_ID & AWS_USER_POOLS_WEB_CLIENT_ID từ cognito vừa tạo:

Thực hiện chạy web với lệnh yarn dev:

Truy cập vào web với đường dẫn http://localhost:3000/auth/login:

Thực hiện tạo tài khoản mới:

Thực hiện verify tài khoản bằng mã otp gửi đến mail vừa tạo:

Truy cập vào resource Cognito xem danh sách user:

Khởi tạo resource DynamoDB

Ở giao diện Dashboard của DynamoDB:

  • Chon Create table

Nhập một số thông tin cho table:

Kết quả sau khi tạo bảng:

Khởi tạo resource SQS

Chọn Create Queue:

Ở mục Details:K

  • Type: Standard

  • Name: KMA-Queue

Tạo Quene thành công:

Thực hiện gửi message:

  • Chọn Send and receive message

Nhập nội dung message và nhấn send:

Ở mục Receive message xem số lượng và thời gian gửi message:

Chọn vào ID để xem nội dung message:

Khởi tạo resource Lambda

Tại màn hình chính Lambda chọn Create function:

Tại mục Basic information:

  • Function name: lambda_post_user

  • Runtime: Node.js 20.x

  • Architecture: x86_64

Function lambda_post_user cần quyền để thực hiện lấy message từ SQS, role này được mình tạo trước đó:

Tạo function lambda_post_user thành công:

Nội dung function lambda để get message từ SQS:

Thực hiện trigger từ SQS sang Lambda

Tại resource SQS:

  • Chọn tab Lambda trigger

  • Chọn Configure Lambda function trigger

Chọn function Lambda lambda_post_user và lưu lại:

Tạo thành công lambda trigger:

Thực hiện send một message:

Dùng Cloudwatch để xem log gửi đến function, nhận message từ queue thành công:

Chỉnh sửa nội dung function lambda_post_user để có thể push dữ liệu vào DynamoDB:

import { DynamoDBClient, PutItemCommand } from "@aws-sdk/client-dynamodb";
const client = new DynamoDBClient({
  region: process.env.REGION,
});
export const handler = async (event) => {
  for (const record of event.Records) {
    const messageBody = record.body;
    console.log("messageBody: ", messageBody);
    const body = JSON.parse(messageBody);
    const input = {
      TableName: process.env.TABLE_NAME,
      Item: {
        id: { S: body.id },
        name: { S: body.name },
      },
      ConditionExpression: "attribute_not_exists(id)",
    };
    const command = new PutItemCommand(input);
    let response = {};
    try {
      response = await client.send(command);
    } catch (e) {
      console.error("error: ", e);
      response = {
        status: 401,
        message: e.message,
      };}
    console.log("response: ", response);
    return response;
  }return { statusCode: 200, body: "Success" };
};

Thử gửi 1 message đối tượng gồm 2 trường id và name:

Kết quả tạo mới 1 user thành công:

Khởi tạo resource API Gateway

Tại dashboard của resource API Gateway, chọn type REST API:

Nhập tên và mô tả cho api mới này:

Chọn Create resource để tạo một resource mới cho api:

Điền thông tin cho resource mới:

Tạo method mới cho resource:

Chọn method POST và type AWS Service:

  • Chọn Region

  • AWS service: Simple Queue Service

  • Nhập Role arn (lưu ý role này phải có quyền send message đến sqs)

Ở phần Mapping template cần thêm 1 template mới để khi nhận được request từ người dùng nó sẽ chỉnh sửa đúng format để gửi đến SQS:

Thực hiện test method vừa tạo:

Kết quả thực hiện send message thành công:

Dữ liệu đã được lưu vào DynamoDB:

Tiếp đến cần tạo Authorizer để xác thực cho api:

  • Chọn tab Authorizers

  • Chọn Create authorizers

Tại phần Authorizer details:

  • Authorizer name: authorizer-cognito-001

  • Type: Cognito

  • Chọn cognito mà bạn đa tạo: KMA_Cognito

    Token source: Authorization (Để là trường header để api xác thực token người dùng)

Chọn Edit cho Method request phương thức POST:

Chọn authorizer vừa tạo cho trường Authorization:

Thực hiện deploy api:

Deploy api thành công:

Thực hiện gửi request đến api mà không có trường authorization:

Nhập giá trị Authorization hợp lệ, gửi request thành công:

Thực hiện tạo các api khác tương tự.'

Kiểm tra ứng dụng

Bước đầu tiên, cần truy cập vào trang web và đăng ký 1 tài khoản mới:

Điền thông tin người dùng:

Nhập mã từ mail để xác thực tài khoản:

Sử dụng app Authenticator quét để sử dụng OTP cho tài khoản:

Tài màn hình chính Quản lý người dùng:

Chọn thêm mới người dùng:

Điền thông tin người dùng mới:

Thêm người dùng mới thành công:

Thực hiện xóa user vừa tạo:

Kết quả:

Sử dụng terraform

Tại đây, bạn có thể sử dụng terraform để tạo các resource ở trên bằng lệnh:

Link source terraform:

Link chứa source terraform cho dự án AWS Serverless

More from this blog

Learn DevOps

21 posts