【AWS】AWS SAMを使いCLIでLambda関数をデプロイ(Typescript)

AWS

1. 概要

前回は「Lambda」と「DynamoDB」をつないでCRUD APIを開発する内容でした。今回は「AWS SAM CLI」を使いLambda関数をデプロイする内容となります。

2. AWSアカウントにサインアップ

2-1. 前提条件

3. AWSアクセスキーの取得

3-1. AWSアクセスキーの取得

4. AWS CLI のインストール

4-1. インストール

5. AWS SAM CLIのインストール

5-1. 「AWS SAM CLI .zip」ファイルを任意のディレクトリにダウンロード

curl -L https://github.com/aws/aws-sam-cli/releases/latest/download/aws-sam-cli-linux-x86_64.zip -o aws-sam-cli-linux-x86_64.zip

5-2. インストールファイルを任意のディレクトリに解凍

unzip aws-sam-cli-linux-x86_64.zip -d sam-installation

5-3. 「AWS SAM CLI」をインストール

sudo ./sam-installation/install

5-4. インストールを確認

sam --version

SAM CLI, version 1.116.0

6. アプリケーションを初期化

6-1. init

sam init
  • プロジェクト名
    • sam-app-example
        SAM CLI now collects telemetry to better understand customer needs.

        You can OPT OUT and disable telemetry collection by setting the
        environment variable SAM_CLI_TELEMETRY=0 in your shell.
        Thanks for your help!

        Learn More: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-telemetry.html


You can preselect a particular runtime or package type when using the `sam init` experience.
Call `sam init --help` to learn more.

Which template source would you like to use?
        1 - AWS Quick Start Templates
        2 - Custom Template Location
Choice: 1

Choose an AWS Quick Start application template
        1 - Hello World Example
        2 - Data processing
        3 - Hello World Example with Powertools for AWS Lambda
        4 - Multi-step workflow
        5 - Scheduled task
        6 - Standalone function
        7 - Serverless API
        8 - Infrastructure event management
        9 - Lambda Response Streaming
        10 - Serverless Connector Hello World Example
        11 - Multi-step workflow with Connectors
        12 - GraphQLApi Hello World Example
        13 - Full Stack
        14 - Lambda EFS example
        15 - DynamoDB Example
        16 - Machine Learning
Template: 1

Use the most popular runtime and package type? (Python and zip) [y/N]: N

Which runtime would you like to use?
        1 - aot.dotnet7 (provided.al2)
        2 - dotnet8
        3 - dotnet6
        4 - go (provided.al2)
        5 - go (provided.al2023)
        6 - graalvm.java11 (provided.al2)
        7 - graalvm.java17 (provided.al2)
        8 - java21
        9 - java17
        10 - java11
        11 - java8.al2
        12 - nodejs20.x
        13 - nodejs18.x
        14 - nodejs16.x
        15 - python3.9
        16 - python3.8
        17 - python3.12
        18 - python3.11
        19 - python3.10
        20 - ruby3.3
        21 - ruby3.2
        22 - rust (provided.al2)
        23 - rust (provided.al2023)
Runtime: 12

What package type would you like to use?
        1 - Zip
        2 - Image
Package type: 1

Based on your selections, the only dependency manager available is npm.
We will proceed copying the template using npm.

Select your starter template
        1 - Hello World Example
        2 - Hello World Example TypeScript
Template: 2

Would you like to enable X-Ray tracing on the function(s) in your application?  [y/N]: N

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

Would you like to set Structured Logging in JSON format on your Lambda functions?  [y/N]: N

Project name [sam-app]: sam-app-example

Cloning from https://github.com/aws/aws-sam-cli-app-templates (process may take a moment)

    -----------------------
    Generating application:
    -----------------------
    Name: sam-app-example
    Runtime: nodejs20.x
    Architectures: x86_64
    Dependency Manager: npm
    Application Template: hello-world-typescript
    Output Directory: .
    Configuration file: sam-app-example/samconfig.toml

    Next steps can be found in the README file at sam-app-example/README.md


Commands you can use next
=========================
[*] Create pipeline: cd sam-app-example && sam pipeline init --bootstrap
[*] Validate SAM template: cd sam-app-example && sam validate
[*] Test Function in the Cloud: cd sam-app-example && sam sync --stack-name {stack-name} --watch

6-2. ディレクトリ構造

cd sam-app-example
.
├── README.md
├── events
│   └── event.json
├── hello-world
│   ├── app.ts
│   ├── jest.config.ts
│   ├── package.json
│   ├── tests
│   │   └── unit
│   │       └── test-handler.test.ts
│   └── tsconfig.json
├── samconfig.toml
└── template.yaml

4 directories, 9 files

6-3. ライブラリのインストール

cd hello-world
npm install
cd ..

7. アプリケーションを構築

7-1. build

sam build
Starting Build use cache
Manifest file is changed (new hash: 3a55b648027d1145164f225fad481127) or dependency folder
(.aws-sam/deps/c19b37ea-01ef-4934-9e07-9446b9b92c09) is missing for (HelloWorldFunction), downloading dependencies and copying/building
source
Building codeuri: /home/sondon/dev/aws/apps/sam-app-example/hello-world runtime: nodejs20.x metadata: {'BuildMethod': 'esbuild',
'BuildProperties': {'Minify': True, 'Target': 'es2020', 'Sourcemap': True, 'EntryPoints': ['app.ts']}} architecture: x86_64 functions:
HelloWorldFunction
 Running NodejsNpmEsbuildBuilder:CopySource
 Running NodejsNpmEsbuildBuilder:NpmInstall
 Running NodejsNpmEsbuildBuilder:EsbuildBundle
 Running NodejsNpmEsbuildBuilder:CleanUp
 Running NodejsNpmEsbuildBuilder:MoveDependencies

Sourcemap set without --enable-source-maps, adding --enable-source-maps to function HelloWorldFunction NODE_OPTIONS

You are using source maps, note that this comes with a performance hit! Set Sourcemap to false and remove NODE_OPTIONS:
--enable-source-maps to disable source maps.


Build Succeeded

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

Commands you can use next
=========================
[*] Validate SAM template: sam validate
[*] Invoke Function: sam local invoke
[*] Test Function in the Cloud: sam sync --stack-name {{stack-name}} --watch
[*] Deploy: sam deploy --guided

7-2. ディレクトリ構造

tree .aws-sam -I "deps|cache"
.aws-sam
├── build
│   ├── HelloWorldFunction
│   │   ├── app.js
│   │   └── app.js.map
│   └── template.yaml
└── build.toml

2 directories, 4 files

8. アプリケーションをAWS クラウドにデプロイ

8-1. deploy

※必要なポリシーを追加

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 [sam-app-example]:
        AWS Region [ap-northeast-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:

        Managed S3 bucket: aws-sam-cli-managed-default-samclisourcebucket-czf78z0qr3am
        A different default S3 bucket can be set in samconfig.toml and auto resolution of buckets turned off by setting resolve_s3=False

        Parameter "stack_name=sam-app-example" in [default.deploy.parameters] is defined as a global parameter
[default.global.parameters].
        This parameter will be only saved under [default.global.parameters] in /home/sondon/dev/aws/apps/sam-app-example/samconfig.toml.

        Saved arguments to config file
        Running 'sam deploy' for future deployments will use the parameters saved above.
        The above parameters can be changed by modifying samconfig.toml
        Learn more about samconfig.toml syntax at
        https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-config.html

        Uploading to sam-app-example/12345678901234567890123456789012  1279 / 1279  (100.00%)

        Deploying with following values
        ===============================
        Stack name                   : sam-app-example
        Region                       : ap-northeast-1
        Confirm changeset            : True
        Disable rollback             : False
        Deployment s3 bucket         : aws-sam-cli-managed-default-samclisourcebucket-123456789012
        Capabilities                 : ["CAPABILITY_IAM"]
        Parameter overrides          : {}
        Signing Profiles             : {}

Initiating deployment
=====================

        Uploading to sam-app-example/23456789012345678901234567890123.template  1445 / 1445  (100.00%)


Waiting for changeset to be created..

CloudFormation stack changeset
-------------------------------------------------------------------------------------------------------------------------------------
Operation                         LogicalResourceId                 ResourceType                      Replacement
-------------------------------------------------------------------------------------------------------------------------------------
+ Add                             HelloWorldFunctionHelloWorldPer   AWS::Lambda::Permission           N/A
                                  missionProd
+ Add                             HelloWorldFunctionRole            AWS::IAM::Role                    N/A
+ Add                             HelloWorldFunction                AWS::Lambda::Function             N/A
+ Add                             ServerlessRestApiDeployment47fc   AWS::ApiGateway::Deployment       N/A
                                  2d5f9d
+ Add                             ServerlessRestApiProdStage        AWS::ApiGateway::Stage            N/A
+ Add                             ServerlessRestApi                 AWS::ApiGateway::RestApi          N/A
-------------------------------------------------------------------------------------------------------------------------------------


Changeset created successfully. arn:aws:cloudformation:ap-northeast-1:123456789012:changeSet/samcli-deploy1714639024/12345678-4e29-4034-8691-123456789012


Previewing CloudFormation changeset before deployment
======================================================
Deploy this changeset? [y/N]: y

2024-05-02 17:37:16 - Waiting for stack create/update to complete

CloudFormation events from stack operations (refresh every 5.0 seconds)
-------------------------------------------------------------------------------------------------------------------------------------
ResourceStatus                    ResourceType                      LogicalResourceId                 ResourceStatusReason
-------------------------------------------------------------------------------------------------------------------------------------
CREATE_IN_PROGRESS                AWS::CloudFormation::Stack        sam-app-example                   User Initiated
CREATE_IN_PROGRESS                AWS::IAM::Role                    HelloWorldFunctionRole            -
CREATE_IN_PROGRESS                AWS::IAM::Role                    HelloWorldFunctionRole            Resource creation Initiated
CREATE_COMPLETE                   AWS::IAM::Role                    HelloWorldFunctionRole            -
CREATE_IN_PROGRESS                AWS::Lambda::Function             HelloWorldFunction                -
CREATE_IN_PROGRESS                AWS::Lambda::Function             HelloWorldFunction                Resource creation Initiated
CREATE_IN_PROGRESS                AWS::Lambda::Function             HelloWorldFunction                Eventual consistency check
                                                                                                      initiated
CREATE_IN_PROGRESS                AWS::ApiGateway::RestApi          ServerlessRestApi                 -
CREATE_IN_PROGRESS                AWS::ApiGateway::RestApi          ServerlessRestApi                 Resource creation Initiated
CREATE_COMPLETE                   AWS::ApiGateway::RestApi          ServerlessRestApi                 -
CREATE_IN_PROGRESS                AWS::Lambda::Permission           HelloWorldFunctionHelloWorldPer   -
                                                                    missionProd
CREATE_IN_PROGRESS                AWS::ApiGateway::Deployment       ServerlessRestApiDeployment47fc   -
                                                                    2d5f9d
CREATE_COMPLETE                   AWS::Lambda::Function             HelloWorldFunction                -
CREATE_IN_PROGRESS                AWS::Lambda::Permission           HelloWorldFunctionHelloWorldPer   Resource creation Initiated
                                                                    missionProd
CREATE_COMPLETE                   AWS::Lambda::Permission           HelloWorldFunctionHelloWorldPer   -
                                                                    missionProd
CREATE_IN_PROGRESS                AWS::ApiGateway::Deployment       ServerlessRestApiDeployment47fc   Resource creation Initiated
                                                                    2d5f9d
CREATE_COMPLETE                   AWS::ApiGateway::Deployment       ServerlessRestApiDeployment47fc   -
                                                                    2d5f9d
CREATE_IN_PROGRESS                AWS::ApiGateway::Stage            ServerlessRestApiProdStage        -
CREATE_IN_PROGRESS                AWS::ApiGateway::Stage            ServerlessRestApiProdStage        Resource creation Initiated
CREATE_COMPLETE                   AWS::ApiGateway::Stage            ServerlessRestApiProdStage        -
CREATE_COMPLETE                   AWS::CloudFormation::Stack        sam-app-example                   -
-------------------------------------------------------------------------------------------------------------------------------------

CloudFormation outputs from deployed stack
---------------------------------------------------------------------------------------------------------------------------------------
Outputs
---------------------------------------------------------------------------------------------------------------------------------------
Key                 HelloWorldFunctionIamRole
Description         Implicit IAM Role created for Hello World function
Value               arn:aws:iam::123456789012:role/sam-app-example-HelloWorldFunctionRole-234567890123

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

Key                 HelloWorldFunction
Description         Hello World Lambda Function ARN
Value               arn:aws:lambda:ap-northeast-1:123456789012:function:sam-app-example-HelloWorldFunction-3456789012345
---------------------------------------------------------------------------------------------------------------------------------------


Successfully created/updated stack - sam-app-example in ap-northeast-1

8-2. Management Consoleで確認

9. アプリケーションを実行

9-1. APIエンドポイントの値を取得

  • 上記8-1ログより「Outputs」を探す
    • Key
      • HelloWorldApi
    • Value
      • https://1234567890.execute-api.ap-northeast-1.amazonaws.com/Prod/hello/
      • これが対象のAPIエンドポイント
  • Management Consoleで確認

9-2. 関数を呼び出し

curl https://1234567890.execute-api.ap-northeast-1.amazonaws.com/Prod/hello/

{“message”:”hello world”}

10. AWSクラウド内の関数とやり取り

10-1. 関数とやり取り

sam remote invoke HelloWorldFunction --stack-name sam-app-example
Invoking Lambda Function HelloWorldFunction
START RequestId: 12345678-b738-4fcd-b04d-123456789012 Version: $LATEST
END RequestId: 12345678-b738-4fcd-b04d-123456789012
REPORT RequestId: 12345678-b738-4fcd-b04d-123456789012  Duration: 1.43 ms       Billed Duration: 2 ms   Memory Size: 128 MB     Max Memory Used: 64 MB
{"statusCode":200,"body":"{\"message\":\"hello world\"}"}

11. AWSクラウドからアプリケーションを削除

※必要に応じ削除

sam delete --stack-name sam-app-example

12. 備考

「AWS SAM CLI」を使いLambda関数をデプロイする内容でした。

13. 参考

  1. AWS Serverless Application Model (AWS SAM) とは何ですか? – AWS Serverless Application Model (amazon.com)

投稿者プロフィール

Sondon
開発好きなシステムエンジニアです。
卓球にハマってます。

関連記事

  1. AWS

    【AWS】APIGatewayのバックアップ、復元

  2. AWS

    【AWS】AWS SAMを使いCLIでDynamoDBやLambda関…

  3. AWS

    【AWS】AWS Step Functions with Lambda…

  4. AWS

    【AWS】AWSアカウントを作成し、マネジメントコンソールにサインイン…

  5. AWS

    NuGetパッケージの管理で「このソースでは利用できません」と表示され…

  6. AWS

    【AWS】Lambdaを使ってみる

最近の記事

  1. Node.js
  2. AWS
  3. AWS

制作実績一覧

  1. Checkeys