【AWS】AWS SAMを使いCLIでDynamoDBやLambda関数のCRUD APIをデプロイ(Typescript)

AWS

1. 概要

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

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

2-1. 前提条件

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

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

4. AWS CLI のインストール

4-1. インストール

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

5-1. インストール

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

6-1. init

sam init
  • プロジェクト名
    • sam-crud-api
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: 7

Which runtime would you like to use?
        1 - dotnet8
        2 - dotnet6
        3 - nodejs20.x
        4 - nodejs18.x
        5 - nodejs16.x
Runtime: 3

Based on your selections, the only Package type available is Zip.
We will proceed to selecting the Package type as Zip.

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

Would you like to enable X-Ray tracing on the function(s) in your application?  [y/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]:

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

Project name [sam-app]: sam-crud-api

    -----------------------
    Generating application:
    -----------------------
    Name: sam-crud-api
    Runtime: nodejs20.x
    Architectures: x86_64
    Dependency Manager: npm
    Application Template: quick-start-web
    Output Directory: .
    Configuration file: sam-crud-api/samconfig.toml

    Next steps can be found in the README file at sam-crud-api/README.md


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

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

cd sam-crud-api
.
├── README.md
├── __tests__
│   └── unit
│       └── handlers
│           ├── get-all-items.test.mjs
│           ├── get-by-id.test.mjs
│           └── put-item.test.mjs
├── buildspec.yml
├── env.json
├── events
│   ├── event-get-all-items.json
│   ├── event-get-by-id.json
│   └── event-post-item.json
├── package.json
├── samconfig.toml
├── src
│   └── handlers
│       ├── get-all-items.mjs
│       ├── get-by-id.mjs
│       └── put-item.mjs
└── template.yaml

6 directories, 15 files

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

npm install

6-4. ソースコードを修正

code .

6-4-1. 「samconfig.toml」にプロパティを1つ追加

[default]
[default.global.parameters]
stack_name = "sam-crud-api"
parameter_overrides = "TargetTable=http-crud-tutorial-items"
  • 「parameter_overrides」を追加

6-4-2. 「template.yaml」にプロパティを1つ追加

Parameters:
  TargetTable:
    Type: String
  • 「Resource」の上に追記

6-4-3. テーブル参照を変更

      Policies:
        # Give Create/Read/Update/Delete Permissions to the SampleTable
        - DynamoDBCrudPolicy:
            TableName: !Ref TargetTable
      Environment:
        Variables:
          # Make table name accessible as environment variable from function code during execution
          SAMPLE_TABLE: !Ref TargetTable
  • 「SampleTable」⇒「TargetTable」

6-4-3. 「SampleTable」ブロックを削除

  SampleTable:
    Type: AWS::Serverless::SimpleTable
    Properties:
      PrimaryKey:
        Name: id
        Type: String
      ProvisionedThroughput:
        ReadCapacityUnits: 2
        WriteCapacityUnits: 2

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

7-1. build

sam build
Starting Build use cache
Manifest file is changed (new hash: 034dd9d287d8b04d2d2681a98a82af3a) or dependency folder
(.aws-sam/deps/9d064037-ec37-4668-ae08-5648df554c53) is missing for (getAllItemsFunction, getByIdFunction, putItemFunction), downloading
dependencies and copying/building source
Building codeuri: /home/sondon/dev/aws/apps/sam-crud-api runtime: nodejs20.x metadata: {} architecture: x86_64 functions:
getAllItemsFunction, getByIdFunction, putItemFunction
 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

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" -L 3
.aws-sam
├── build
│   ├── getAllItemsFunction
│   │   ├── README.md
│   │   ├── __tests__
│   │   ├── buildspec.yml
│   │   ├── env.json
│   │   ├── events
│   │   ├── node_modules
│   │   ├── package-lock.json
│   │   ├── package.json
│   │   ├── samconfig.toml
│   │   ├── src
│   │   └── template.yaml
│   ├── getByIdFunction
│   │   ├── README.md
│   │   ├── __tests__
│   │   ├── buildspec.yml
│   │   ├── env.json
│   │   ├── events
│   │   ├── node_modules
│   │   ├── package-lock.json
│   │   ├── package.json
│   │   ├── samconfig.toml
│   │   ├── src
│   │   └── template.yaml
│   ├── putItemFunction
│   │   ├── README.md
│   │   ├── __tests__
│   │   ├── buildspec.yml
│   │   ├── env.json
│   │   ├── events
│   │   ├── node_modules
│   │   ├── package-lock.json
│   │   ├── package.json
│   │   ├── samconfig.toml
│   │   ├── src
│   │   └── template.yaml
│   └── template.yaml
└── build.toml

16 directories, 23 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-crud-api]:
        AWS Region [ap-northeast-1]:
        Parameter TargetTable [http-crud-tutorial-items]:
        #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]:
        getAllItemsFunction has no authentication. Is this okay? [y/N]: y
        getByIdFunction has no authentication. Is this okay? [y/N]: y
        putItemFunction 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-abcdefghijkl
        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-crud-api" 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-crud-api/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-crud-api/fe83f43b4a5a9425733a936d53ccd5c7  2722961 / 2722961  (100.00%)
File with same data already exists at sam-crud-api/fe83f43b4a5a9425733a936d53ccd5c7, skipping upload
File with same data already exists at sam-crud-api/fe83f43b4a5a9425733a936d53ccd5c7, skipping upload

        Deploying with following values
        ===============================
        Stack name                   : sam-crud-api
        Region                       : ap-northeast-1
        Confirm changeset            : True
        Disable rollback             : False
        Deployment s3 bucket         : aws-sam-cli-managed-default-samclisourcebucket-abcdefghijkl
        Capabilities                 : ["CAPABILITY_IAM"]
        Parameter overrides          : {"TargetTable": "http-crud-tutorial-items"}
        Signing Profiles             : {}

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

        Uploading to sam-crud-api/c927188c599414524c2070cc32a7218b.template  2805 / 2805  (100.00%)


Waiting for changeset to be created..

CloudFormation stack changeset
-------------------------------------------------------------------------------------------------------------------------------------
Operation                         LogicalResourceId                 ResourceType                      Replacement
-------------------------------------------------------------------------------------------------------------------------------------
+ Add                             ServerlessRestApiDeploymenta4d3   AWS::ApiGateway::Deployment       N/A
                                  59a69a
+ Add                             ServerlessRestApiProdStage        AWS::ApiGateway::Stage            N/A
+ Add                             ServerlessRestApi                 AWS::ApiGateway::RestApi          N/A
+ Add                             getAllItemsFunctionApiPermissio   AWS::Lambda::Permission           N/A
                                  nProd
+ Add                             getAllItemsFunctionRole           AWS::IAM::Role                    N/A
+ Add                             getAllItemsFunction               AWS::Lambda::Function             N/A
+ Add                             getByIdFunctionApiPermissionPro   AWS::Lambda::Permission           N/A
                                  d
+ Add                             getByIdFunctionRole               AWS::IAM::Role                    N/A
+ Add                             getByIdFunction                   AWS::Lambda::Function             N/A
+ Add                             putItemFunctionApiPermissionPro   AWS::Lambda::Permission           N/A
                                  d
+ Add                             putItemFunctionRole               AWS::IAM::Role                    N/A
+ Add                             putItemFunction                   AWS::Lambda::Function             N/A
-------------------------------------------------------------------------------------------------------------------------------------


Changeset created successfully. arn:aws:cloudformation:ap-northeast-1:123456789012:changeSet/samcli-deploy1715249737/42688e90-4343-4b50-874a-8048edbac4c9


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

2024-05-09 19:15:55 - 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-crud-api                      User Initiated
CREATE_IN_PROGRESS                AWS::IAM::Role                    getAllItemsFunctionRole           -
CREATE_IN_PROGRESS                AWS::IAM::Role                    getByIdFunctionRole               -
CREATE_IN_PROGRESS                AWS::IAM::Role                    putItemFunctionRole               -
CREATE_IN_PROGRESS                AWS::IAM::Role                    getAllItemsFunctionRole           Resource creation Initiated
CREATE_IN_PROGRESS                AWS::IAM::Role                    getByIdFunctionRole               Resource creation Initiated
CREATE_IN_PROGRESS                AWS::IAM::Role                    putItemFunctionRole               Resource creation Initiated
CREATE_COMPLETE                   AWS::IAM::Role                    getAllItemsFunctionRole           -
CREATE_COMPLETE                   AWS::IAM::Role                    getByIdFunctionRole               -
CREATE_COMPLETE                   AWS::IAM::Role                    putItemFunctionRole               -
CREATE_IN_PROGRESS                AWS::Lambda::Function             getAllItemsFunction               -
CREATE_IN_PROGRESS                AWS::Lambda::Function             getByIdFunction                   -
CREATE_IN_PROGRESS                AWS::Lambda::Function             putItemFunction                   -
CREATE_IN_PROGRESS                AWS::Lambda::Function             getByIdFunction                   Resource creation Initiated
CREATE_IN_PROGRESS                AWS::Lambda::Function             getAllItemsFunction               Resource creation Initiated
CREATE_IN_PROGRESS                AWS::Lambda::Function             putItemFunction                   Resource creation Initiated
CREATE_IN_PROGRESS                AWS::Lambda::Function             getByIdFunction                   Eventual consistency check
                                                                                                      initiated
CREATE_IN_PROGRESS                AWS::Lambda::Function             getAllItemsFunction               Eventual consistency check
                                                                                                      initiated
CREATE_IN_PROGRESS                AWS::Lambda::Function             putItemFunction                   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::ApiGateway::Deployment       ServerlessRestApiDeploymenta4d3   -
                                                                    59a69a
CREATE_IN_PROGRESS                AWS::Lambda::Permission           putItemFunctionApiPermissionPro   -
                                                                    d
CREATE_IN_PROGRESS                AWS::Lambda::Permission           getByIdFunctionApiPermissionPro   -
                                                                    d
CREATE_IN_PROGRESS                AWS::Lambda::Permission           getAllItemsFunctionApiPermissio   -
                                                                    nProd
CREATE_COMPLETE                   AWS::Lambda::Function             getByIdFunction                   -
CREATE_COMPLETE                   AWS::Lambda::Function             getAllItemsFunction               -
CREATE_COMPLETE                   AWS::Lambda::Function             putItemFunction                   -
CREATE_IN_PROGRESS                AWS::Lambda::Permission           putItemFunctionApiPermissionPro   Resource creation Initiated
                                                                    d
CREATE_IN_PROGRESS                AWS::Lambda::Permission           getAllItemsFunctionApiPermissio   Resource creation Initiated
                                                                    nProd
CREATE_IN_PROGRESS                AWS::Lambda::Permission           getByIdFunctionApiPermissionPro   Resource creation Initiated
                                                                    d
CREATE_COMPLETE                   AWS::Lambda::Permission           putItemFunctionApiPermissionPro   -
                                                                    d
CREATE_COMPLETE                   AWS::Lambda::Permission           getByIdFunctionApiPermissionPro   -
                                                                    d
CREATE_IN_PROGRESS                AWS::ApiGateway::Deployment       ServerlessRestApiDeploymenta4d3   Resource creation Initiated
                                                                    59a69a
CREATE_COMPLETE                   AWS::Lambda::Permission           getAllItemsFunctionApiPermissio   -
                                                                    nProd
CREATE_COMPLETE                   AWS::ApiGateway::Deployment       ServerlessRestApiDeploymenta4d3   -
                                                                    59a69a
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-crud-api                      -
-------------------------------------------------------------------------------------------------------------------------------------

CloudFormation outputs from deployed stack
---------------------------------------------------------------------------------------------------------------------------------------
Outputs
---------------------------------------------------------------------------------------------------------------------------------------
Key                 WebEndpoint
Description         API Gateway endpoint URL for Prod stage
Value               https://abcdefghij.execute-api.ap-northeast-1.amazonaws.com/Prod/
---------------------------------------------------------------------------------------------------------------------------------------


Successfully created/updated stack - sam-crud-api in ap-northeast-1

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

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

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

9-2. データを登録

curl -X "POST" -H "Content-Type: application/json" -d "{\"id\": \"123\", \"price\": 12345, \"name\": \"myitem\"}" https://abcdefghij.execute-api.ap-northeast-1.amazonaws.com/Prod

{“id”:”123″,”price”:12345,”name”:”myitem”}

9-3. 全件取得

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

[{“id”:”123″,”name”:”myitem”}]

9-4. 1件取得

curl https://abcdefghij.execute-api.ap-northeast-1.amazonaws.com/Prod/123

{“id”:”123″,”name”:”myitem”}

10. Management Consoleで確認

10-1. 画面で確認

  • Cloud Formation
  • Api Gateway
  • Lambda Function
  • DynamoDB

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

※必要に応じ削除

sam delete --stack-name sam-crud-api

12. 備考

「AWS SAM CLI」を使いLambda関数とDynamoDBをつないで作成したAPIをデプロイする内容でした。

13. 参考

  1. AWS Serverless Application Model (AWS SAM) とは何ですか? – AWS Serverless Application Model (amazon.com)
  2. Lambda 環境変数の使用 – AWS Lambda (amazon.com)

関連記事

  1. AWS

    【AWS】Redash on EC2 が突然 502 Bad Gate…

  2. AWS

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

  3. AWS

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

  4. AWS

    【AWS】AWS LambdaとAmazon DynamoDBを使って…

  5. AWS

    【AWS】Amazon DynamoDBを使ってみる(Manageme…

  6. AWS

    【AWS】Amazon DynamoDBを使ってみる(CLI、API)…

最近の記事

  1. AWS
  2. AWS
  3. AWS
  4. AWS
  5. AWS
  6. AWS
  7. AWS
  8. AWS

制作実績一覧

  1. Checkeys