Tạp chí Thợ Code

Ứng dụng Hello World trên AWS Serverless Application Model - Phần 1: Khởi tạo và Deploy thủ công

Nhoáng cái lại thứ tư rồi, điều tuyệt vời của ngày thứ tư đó là chỉ còn hai ngày nữa lại đến cuối tuần, và để giải trí giữa tuần, mời quý anh chị em vọc chơi Cloud9 để tạo một ứng dụng cùng với AWS Serverless Application Model (SAM) hết sức tiện lợi dễ dàng quản lý.

画像が読み込まれない場合はページを更新してみてください。

Source: https://aws.amazon.com/serverless/aws-sam/

AWS Serverless Application Model (SAM) giúp cho:

  • Đơn giản hóa: SAM cung cấp cú pháp đơn giản, cho phép bạn dễ dàng định nghĩa tài nguyên serverless chỉ bằng vài dòng mã YAML.
  • Tích hợp với CloudFormation: SAM thực chất là một mở rộng của AWS CloudFormation, do đó nó tận dụng được toàn bộ sức mạnh của CloudFormation, bao gồm khả năng triển khai, quản lý và cập nhật tài nguyên.
  • Local Testing: SAM cung cấp công cụ cho phép bạn chạy và kiểm tra ứng dụng serverless ngay trên máy tính cá nhân trước khi triển khai lên AWS.

Sử dụng IDE trên Cloud9

AWS Cloud9 là một môi trường phát triển tích hợp (IDE - Integrated Development Environment) dựa trên đám mây, cho phép bạn viết, chạy và gỡ lỗi mã trực tiếp trong trình duyệt web. AWS Cloud9 hỗ trợ nhiều ngôn ngữ lập trình như Python, JavaScript, PHP, và C++, giúp dễ dàng phát triển ứng dụng cho AWS mà không cần thiết lập môi trường phát triển cục bộ.

Khởi tạo

Từ AWS Console > Cloud9 > Create environment:

  • Environment type: New EC2 Instance
  • Instance type: t2.micro
  • Platform: Amazon Linux 2023
画像が読み込まれない場合はページを更新してみてください。

Sau khi hoàn tất việc tạo môi trường, bấm nút Open in Cloud 9 để mở IDE, giao diện sẽ tương tự như minh họa bên dưới.

画像が読み込まれない場合はページを更新してみてください。

Cập nhật SAM CLI

Mặc định SAM CLI trên Cloud9 chưa được cập nhật phiên bản mới, để đảm bảo cho mọi thứ được suôn sẻ chúng ta cần cập nhật phiên bản mới.

画像が読み込まれない場合はページを更新してみてください。

Chạy lệnh bên dưới để tải xuống một script Bash và thực thi nó.

curl 'https://static.us-east-1.prod.workshops.aws/public/1d9be5f3-006d-47cd-bd23-bdc7436c4fb0/static/bin/bootstrap.sh' | bash

File .sh này sẽ thực hiện:

1. Cập nhật hệ thống (update_system)

  • Cập nhật các gói hệ thống thông qua lệnh yum update -y --skip-broken.

2. Cập nhật Python và AWS CLI (update_python_packages)

  • Cập nhật pipsetuptools (các công cụ quản lý và phân phối gói Python).
  • Cài đặt phiên bản mới nhất của AWS CLI (Công cụ dòng lệnh AWS) và xóa phiên bản cũ trong /usr/bin.

3. Cài đặt Pyenv (install_pyenv)

  • Cài đặt các công cụ phát triển liên quan đến Python (như Development Tools, openssl-devel, v.v.).
  • Cài đặt Pyenv (một công cụ quản lý nhiều phiên bản Python trên một hệ thống).
  • Cài đặt Python phiên bản 3.10.11 thông qua Pyenv.

4. Cài đặt công cụ tiện ích (install_utility_tools)

  • Cài đặt công cụ jq (một tiện ích dùng để xử lý dữ liệu JSON từ dòng lệnh).

5. Nâng cấp AWS SAM CLI (upgrade_sam_cli)

  • Tải xuống phiên bản mới nhất của AWS SAM CLI từ GitHub và cài đặt nó.
  • Cập nhật đường dẫn tới SAM CLI trong Cloud9 IDE để hỗ trợ các lệnh như sam local invoke.

6. Cài đặt Maven (install_maven)

  • Tải xuống và cài đặt Maven phiên bản 3.9.6, một công cụ build dự án phổ biến trong Java.
  • Thêm Maven vào biến môi trường PATH để có thể sử dụng từ dòng lệnh.

7. Dọn dẹp sau khi cài đặt (cleanup)

  • Xóa các tệp và thư mục không cần thiết sau khi cài đặt SAM CLI.

8. Kết thúc và khởi động lại shell (main)

  • Sau khi tất cả các bước trên hoàn thành, script sẽ khởi động lại shell để áp dụng các thay đổi.

画像が読み込まれない場合はページを更新してみてください。

Chạy lệnh sam --version để kiểm tra cài đặt. Nếu thấy tương tự minh họa thì mọi thứ đã ổn.

画像が読み込まれない場合はページを更新してみてください。

Xây dựng ứng dụng trên SAM (Serverless Application Model)

Tạo ứng dụng Hello World với template

Với mục tiêu trải nghiệm SAM, chúng ta sẽ xây dựng một ứng dụng đơn giản chạy trên Lambda cùng với những services như trong kiến trúc bên dưới.

画像が読み込まれない場合はページを更新してみてください。

Từ Terminal trên Cloud9 chạy lệnh sam init để khởi tạo dự án. Chọn 1 - AWS Quick Start Templates, tiếp đến chọn 1 - Hello World Example. Chọn no khi được hỏi Use the most popular runtime and package type? (Python and zip) [y/N], mục tiêu để chúng ta có thể dễ dàng tùy chỉnh phiên bản runtime.

Các lựa chọn cấu hình tiếp theo như bên dưới.

Which runtime would you like to use?      
        11 - nodejs20.x

What package type would you like to use? #Lambda function của bạn sẽ được đóng gói dưới dạng file ZIP và tải lên AWS Lambda. Đây là cách phổ biến để đóng gói mã nguồn và các dependency đi kèm với hàm Lambda.
        1 - Zip

Select your starter template
        1 - Hello World Example

Would you like to enable X-Ray tracing on the function(s) in your application?  [y/N]: n
# AWS X-Ray là dịch vụ theo dõi và ghi lại các yêu cầu HTTP trong ứng dụng của bạn, giúp bạn phân tích lỗi và theo dõi hiệu suất của các hàm Lambda.

Would you like to enable monitoring using CloudWatch Application Insights?
For more info, please view https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch-application-insights.html [y/N]: n
# CloudWatch Application Insights cung cấp khả năng giám sát ứng dụng, phát hiện các sự cố tiềm ẩn và tự động thiết lập các cảnh báo.

Would you like to set Structured Logging in JSON format on your Lambda functions?  [y/N]: n
# Structured Logging cho phép ghi nhật  (log) của hàm Lambda theo định dạng JSON. Điều này giúp dễ dàng phân tích và tìm kiếm log hơn, đặc biệt là khi sử dụng CloudWatch Logs hoặc các công cụ phân tích log khác.

Nếu thành công, chúng ta sẽ có thư mục tương như hình minh họa được tạo

画像が読み込まれない場合はページを更新してみてください。

Dự án Hello World SAM chúng ta vừa khởi tạo tạo ra một Lambda function và một API Gateway với endpoint là /hello. Khi được gọi với giao thức HTTP GET, API Gateway sẽ gọi đến Lambda function, Lambda function này cùng với IAM role có quyền sẽ có thể gọi đến các AWS service khác như là Database hay S3 Bucket.

Tìm hiểu cấu trúc ứng dụng
SAM Template

Trong thư mục vừa được tạo trên Cloud9 IDE, bạn sẽ thấy file template.yaml.

File template.yml này là một AWS SAM (Serverless Application Model) template dùng để định nghĩa các tài nguyên AWS cần thiết cho ứng dụng serverless của bạn. File này thực chất là một file IaC (Infrastructure as Code) của AWS CloudFormation.

Phần quan trọng nhất là Resources: HelloWorldFunction

  • Đây là định nghĩa của một hàm AWS Lambda.
    • Type: AWS::Serverless::Function: Xác định rằng đây là một hàm Lambda được định nghĩa bằng AWS SAM.
    • Properties:
      • CodeUri: hello-world/: Thư mục chứa mã nguồn của hàm Lambda (code Node.js nằm trong thư mục hello-world/).
      • Handler: app.lambdaHandler: Đây là entry point của hàm Lambda. AWS sẽ chạy hàm lambdaHandler trong file app.js.
      • Runtime: nodejs20.x: Chạy hàm Lambda trên Node.js phiên bản 20.x.
      • Architectures: x86_64: Chỉ định kiến trúc CPU cho Lambda (ở đây là x86-64).
      • Events:
        • HelloWorld: Đây là sự kiện API Gateway kích hoạt Lambda khi có yêu cầu HTTP.
          • Type: Api: Đây là loại sự kiện API Gateway.
          • Properties:
            • Path: /hello: API sẽ kích hoạt khi người dùng truy cập đường dẫn /hello.
            • Method: get: Chỉ định rằng yêu cầu HTTP là phương thức GET.

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  thocode-sam-app

  Sample SAM Template for thocode-sam-app
  
# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
  Function:
    Timeout: 3

Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      CodeUri: hello-world/
      Handler: app.lambdaHandler
      Runtime: nodejs20.x
      Architectures:
        - x86_64
      Events:
        HelloWorld:
          Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
          Properties:
            Path: /hello
            Method: get

Outputs:
  # ServerlessRestApi is an implicit API created out of Events key under Serverless::Function
  # Find out more about other implicit resources you can reference within SAM
  # https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api
  HelloWorldApi:
    Description: "API Gateway endpoint URL for Prod stage for Hello World function"
    Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
  HelloWorldFunction:
    Description: "Hello World Lambda Function ARN"
    Value: !GetAtt HelloWorldFunction.Arn
  HelloWorldFunctionIamRole:
    Description: "Implicit IAM Role created for Hello World function"
    Value: !GetAtt HelloWorldFunctionRole.Arn
Lambda code

File app.mjs là file chứa code logic thực thi.

export const lambdaHandler = async (event, context) => {
    const response = {
      statusCode: 200,
      body: JSON.stringify({
        message: 'hello world',
      })
    };

    return response;
  };

Chạy ứng dụng trên môi trường phát triển (local)

Điều tuyệt vời của AWS SAM là chúng ta có thể chạy ứng dụng trên môi trường phát triển (local) để thử nghiệm, để debug trước khi deploy lên production.

Từ Terminal trên Cloud9 IDE, chuyển đến thư mục chứa source code vừa tạo rồi chạy lệnh npm install để cài đặt các package cần thiết cho NodeJS.

Có một thư mục tên là environment cùng với thư mục con là thư mục ứng dụng vừa tạo ở trên (trong bài này là thocode-sam-app) được tạo mặc định, bạn hãy chuyển đến thư mục này rồi chạy lệnh sam local invoke --event events/event.json.

Một file image sẽ được pull về để tạo môi trường giả lập chạy Lambda.

画像が読み込まれない場合はページを更新してみてください。
$ sam local invoke --event events/event.json
Invoking app.lambdaHandler (nodejs20.x)                                                                                                                                                                                          
Local image was not found.                                                                                                                                                                                                       
Removing rapid images for repo public.ecr.aws/sam/emulation-nodejs20.x                                                                                                                                                           
Building image......
Using local image: public.ecr.aws/lambda/nodejs:20-rapid-x86_64.                                                                                                                                                                 
                                                                                                                                                                                                                                 
Mounting /home/ec2-user/environment/thocode-sam-app/hello-world as /var/task:ro,delegated, inside runtime container                                                                                                              
START RequestId: c7164aae-ae1b-4a99-b6ae-965484790705 Version: $LATEST
END RequestId: fc5168cf-837c-439c-9949-e7b689150d1c
REPORT RequestId: fc5168cf-837c-439c-9949-e7b689150d1c  Init Duration: 0.02 ms  Duration: 264.26 ms     Billed Duration: 265 ms Memory Size: 128 MB     Max Memory Used: 128 MB
{"statusCode": 200, "body": "{\"message\":\"hello world\"}"}

Để giả lập API Gateway, chúng ta chạy lệnh sam local start-api --port 8080 để run một HTTP server.

Initializing the lambda functions containers.                                                                                                                                                                                    
Local image is up-to-date                                                                                                                                                                                                        
Using local image: public.ecr.aws/lambda/nodejs:20-rapid-x86_64.                                                                                                                                                                 
                                                                                                                                                                                                                                 
Mounting /home/ec2-user/environment/thocode-sam-app/hello-world as /var/task:ro,delegated, inside runtime container                                                                                                              
Containers Initialization is done.                                                                                                                                                                                               
Mounting HelloWorldFunction at http://127.0.0.1:8080/hello [GET]    

Chúng ta có thể dùng lệnh curl http://localhost:8080/hello để test end point vừa chạy thông qua HTTP Server. Hoặc trực quan hơn, tại Cloud9 IDE chọn menu Tools > Preview > Preview Running Application để mở trình duyệt web.

画像が読み込まれない場合はページを更新してみてください。

Deploy ứng dụng

Vẫn tại thư mục ~/environment/thocode-sam-app chạy lệnh sam build để build ứng dụng, tương tự như lệnh npm run build khi xây dựng các ứng dụng ReactJS/ NodeJS chúng ta thường hay chạy trên local.

$ sam build
Starting Build use cache                                                                                                                                                                                                         
Manifest file is changed (new hash: xxx) or dependency folder (.aws-sam/deps/bb62309b-xxx) is missing for (HelloWorldFunction), downloading dependencies and                
copying/building source                                                                                                                                                                                                          
Building codeuri: /home/ec2-user/environment/thocode-sam-app/hello-world runtime: nodejs20.x architecture: x86_64 functions: HelloWorldFunction                                                                                  
 Running NodejsNpmBuilder:NpmPack                                                                                                                                                                                                
 Running NodejsNpmBuilder:CopyNpmrcAndLockfile                                                                                                                                                                                   
 Running NodejsNpmBuilder:CopySource                                                                                                                                                                                             
 Running NodejsNpmBuilder:NpmInstall                                                                                                                                                                                             
 Running NodejsNpmBuilder:CleanUp                                                                                                                                                                                                
 Running NodejsNpmBuilder:CopyDependencies                                                                                                                                                                                       
 Running NodejsNpmBuilder:CleanUpNpmrc                                                                                                                                                                                           
 Running NodejsNpmBuilder:LockfileCleanUp                                                                                                                                                                                        
 Running NodejsNpmBuilder:LockfileCleanUp                                                                                                                                                                                        

Build Succeeded

Built Artifacts  : .aws-sam/build
Built Template   : .aws-sam/build/template.yaml

Khi build thành công, ngoài log tương tự như trên, bạn có thể kiểm tra thư mục .aws-sam vừa được tạo ra bằng cách Show Hidden Files.

画像が読み込まれない場合はページを更新してみてください。

Tiếp theo, chạy lệnh sam deploy --guided để bắt đầu quá trình deploy ứng dụng. Trả lời các câu hỏi cấu hình như bên dưới.

SAM CLI sẽ thay bạn xử lý các việc sau:

  • Nén toàn bộ source code (kể các các packages) dưới dạng zip
  • Tạo S3 Bucket và upload file zip bên trên lên đó
  • Tạo packaged template với đường dẫn đến file zip vừa upload trên S3, file packaged template này cũng được upload lên S3 Bucket bên trên luôn.
  • Sử dụng CloudFormation ChangeSets để deploy ứng dụng.
$ sam deploy --guided

Configuring SAM deploy
======================

Looking for config file [samconfig.toml] :  Found
Reading default arguments  :  Success

Setting default arguments for 'sam deploy'
=========================================
Stack Name [thocode-sam-app]: 
AWS Region [us-east-1]: 
#Shows you resources changes to be deployed and require a 'Y' to initiate deploy
Confirm changes before deploy [Y/n]: 
#SAM needs permission to be able to create roles to connect to the resources in your template
Allow SAM CLI IAM role creation [Y/n]: 
#Preserves the state of previously provisioned resources when an operation fails
Disable rollback [y/N]: 
HelloWorldFunction has no authentication. Is this okay? [y/N]: y
Save arguments to configuration file [Y/n]: 
SAM configuration file [samconfig.toml]: 
SAM configuration environment [default]: 

Looking for resources needed for deployment:
Creating the required resources...
Successfully created!

Chúng ta sẽ thấy kết quả như bên dưới, với thông tin endpoint của API Gateway.

CloudFormation outputs from deployed stack
Outputs

Key                 HelloWorldFunctionIamRole                                                                                                                                                                                
Description         Implicit IAM Role created for Hello World function                                                                                                                                                       
Value               arn:aws:iam::xxx:role/thocode-sam-app-HelloWorldFunctionRole-xxx                                                                                                                       

Key                 HelloWorldApi                                                                                                                                                                                            
Description         API Gateway endpoint URL for Prod stage for Hello World function                                                                                                                                         
Value               https://xxx.execute-api.us-east-1.amazonaws.com/Prod/hello/                                                                                                                                       

Key                 HelloWorldFunction                                                                                                                                                                                       
Description         Hello World Lambda Function ARN                                                                                                                                                                          
Value               arn:aws:lambda:us-east-1:xxx:function:thocode-sam-app-HelloWorldFunction-xxx

Successfully created/updated stack - thocode-sam-app in us-east-1

Dọn dẹp

Chạy lệnh sam delete để dọn dẹp các service vừa khởi tạo.

Biên soạn: Tí Dev.

Hiệu đính & bắt lỗi chính tả: Anh Dũng.

Sài Gòn, những ngày đầu tháng 10/2024 trưa thì nóng chiều thì mưa lác đác.