SAMを利用したLambdaのサーバーレス環境の構築

Go言語
目次

SAMとは?

複数のLambdaの関数を管理するAWSのサービス

AWS サーバーレスアプリケーションモデル (SAM、Serverless Application Model) は、サーバーレスアプリケーション構築用のオープンソースフレームワークです。

複数のLambdaを管理することができるため、deployやプロジェクトの管理がしやすいのがメリットです

AWS サーバーレスアプリケーションモデル (SAM、Serverless Application Model) は、サーバーレスアプリケーション構築用のオープンソースフレームワークです。迅速に記述可能な構文で関数、API、データベース、イベントソースマッピングを表現できます。リソースごとにわずか数行で、任意のアプリケーションを定義して YAML を使用してモデリングできます。デプロイ中、SAM が SAM 構文を AWS CloudFormation 構文に変換および拡張することで、サーバーレスアプリケーションの構築を高速化することができます。

AWS公式

SAMコマンドを利用する準備

最新版にアップデート

まずSAMコマンドが入っているか確認のために、下記のコマンドで最新バージョンに更新していきます

$ brew upgrade aws-sam-cli


#インストール済み場合
Warning: aws/tap/aws-sam-cli 1.61.0 already installed 

#インストールされていない場合
Error: No available formula with the name "aws-sam-cli". Did you mean aws-sdk-cpp?

samのインストール

インストールが必要な場合は、下記のコマンドを実行します

AWSの公式情報に記載されているので、一度最新版を確認することをおすすめします。

インストール手順

# インストールする
$ brew tap aws/tap // これがないと失敗します
$ brew install aws-sam-cli


$ sam --version
SAM CLI, version 1.66.0

インストールが完了したとたところで、バージョンを確認します。

$ sam --version
SAM CLI, version 1.61.0

これで無事にインストールされました。

SAMを利用したLambdaのプロジェクト作成

sam initを実行します

$sam init

        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: 

どのテンプレートを利用するか聞かれます。AWSが用意しているAWS Quick Start Templatesを利用してサクッと開発を進めていきます

どのテンプレートソースを使用したいですか?
Which template source would you like to use?
        1 - AWS Quick Start Templates
        2 - Custom Template Location
Choice: 1 // 1を選択

// Pythonではないので飛ばす
Use the most popular runtime and package type? (Python and zip) [y/N]: n

テンプレートの例が出てくるので、golangに対応していないものが多いので、1を選択します

// AWS Quick Startアプリケーションのテンプレートを選択する
Choose an AWS Quick Start application template 
        1 - Hello World Example
        2 - Multi-step workflow
        3 - Serverless API
        4 - Scheduled task
        5 - Standalone function
        6 - Data processing
        7 - Infrastructure event management
        8 - Serverless Connector Hello World Example
        9 - Multi-step workflow with Connectors
        10 - Lambda EFS example
        11 - Machine Learning
Template: 1

言語の選択肢がでてくるので、Go言語を指定します
今回はgo1.xを選択します。

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

Which runtime would you like to use?
        1 - dotnet6
        2 - dotnet5.0
        3 - dotnetcore3.1
        4 - go1.x
        5 - graalvm.java11 (provided.al2)
        6 - graalvm.java17 (provided.al2)
        7 - java11
        8 - java8.al2
        9 - java8
        10 - nodejs16.x
        11 - nodejs14.x
        12 - nodejs12.x
        13 - python3.9
        14 - python3.8
        15 - python3.7
        16 - ruby2.7
        17 - rust (provided.al2)
Runtime: 4

Dockerイメージを作るわけではないので、1のzipを選択します

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


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

プロジェクト名を入力します

// プロジェクト名を入力
Project name [sam-app]: 

これでプロジェクトが作成されました

local環境でAPIを実行する

ローカル環境でAPIGatewayを通して、Lamdbaの動作を確認するには次のコマンドで起動します

$sam local start-api

Mounting HelloWorldFunction at http://127.0.0.1:3000/hello [GET]
You can now browse to the above endpoints to invoke your functions. You do not need to restart/reload SAM CLI while working on your functions, changes will be reflected instantly/automatically. You only need to restart SAM CLI if you update your AWS SAM template
2022-11-26 18:02:00  * Running on http://127.0.0.1:3000/ (Press CTRL+C to quit)

API Gatewayを介さずにLambdaを直接起動する場合は、下記のように実行します

$ sam local invoke "HelloWorldFunction" -e events/event.json

Invoking app.lambda_handler (python3.9)
Image was not found.
Removing rapid images for repo public.ecr.aws/sam/emulation-python3.9
Building image.........................................................................................................................................................................................................................................
Skip pulling image and use local one: public.ecr.aws/sam/emulation-python3.9:rapid-1.61.0-x86_64.

Mounting /sam-app-example/hello_world as /var/task:ro,delegated inside runtime container
START RequestId: 25d0cf5c-3374-46fb-864b-4ee7643bd77c Version: $LATEST
END RequestId: 25d0cf5c-3374-46fb-864b-4ee7643bd77c
REPORT RequestId: 25d0cf5c-3374-46fb-864b-4ee7643bd77c  Init Duration: 0.46 ms  Duration: 246.31 ms  Billed Duration: 247 ms Memory Size: 128 MB     Max Memory Used: 128 MB
{"statusCode": 200, "body": "{\"message\": \"hello world\"}"}

ビルド

コードの更新があったら、sam buildでビルドし直します。

$ sam build

デプロイ前には必ずやるようにします。

template.yamlの更新

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

  Sample SAM Template for sam-app-example

# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
  Function:
    Timeout: 5

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: hello-world
      Runtime: go1.x
      Architectures:
        - x86_64
      Events:
        CatchAll:
          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: /echo
            Method: GET
      Environment: # More info about Env Vars: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#environment-object
        Variables:
          PARAM1: VALUE
      Role: #IAMロールを記述

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 environment for First Function"
    Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
  HelloWorldFunction:
    Description: "First Lambda Function ARN"
    Value: !GetAtt HelloWorldFunction.Arn
  # HelloWorldFunctionIamRole:
  #   Description: "Implicit IAM Role created for Hello World function"
  #   Value: !GetAtt HelloWorldFunctionRole.Arn

SAMでデプロイ

AWSのアクセスキーを切り替えるための準備

$ cd ~/.aws
$ vim credentials

// 追加
[test] 切り替えようの名前
aws_access_key_id=aws_access_key_idの値
aws_secret_access_key=aws_secret_access_keyの値

この設定を追加することにより、–profileオプションで設定したアクセスキーに切り替えてコマンドを実行できる

--profile test 

初回デプロイは–guidedを付与する

awsのアクセスキーを切り替える必要がある場合は下記で設定しておきます。

$ sam build

初回デプロイ時にデプロイ設定のファイルであるtomlを生成したいので、

–guidedオプションを使ってデプロイをします。

$sam deploy --guided --s3-bucket バケット名 --profile credentialsで設定したプロファイル名 --stack-name プロジェクト名

–guidedオプションを利用したため、下記のように設定項目をヒヤリングされます。

$ sam deploy --guided  --s3-bucket バケット名 --profile test --stack-name sam-app

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

        Looking for config file [samconfig.toml] :  Not found

        Setting default arguments for 'sam deploy'
        =========================================
        // アプリ名を聞かれます
        Stack Name [sam-app]: アプリ名

        // デプロイ先のリージョンを聞かれます
        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]: y //デプロイする時に確認するか
        #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]: n // ロールを作成するか? ロールは事前に用意しておくので、nにします。
        Capabilities [['CAPABILITY_IAM']]: // そのままエンターして、デフォルト値を利用します。
        #Preserves the state of previously provisioned resources when an operation fails
        Disable rollback [y/N]: y
        Save arguments to configuration file [Y/n]: y
        SAM configuration file [samconfig.toml]: //samconfig.tomlで問題ないので、デフォルトのまま進みます
        SAM configuration environment [default]:

下記のエラーが発生した場合は、–guidedオプションなしで再度実施してみます。

Error: Unable to upload artifact HelloWorldFunction referenced by CodeUri parameter of HelloWorldFunction resource.
An error occurred (AccessDenied) when calling the PutObject operation: Access Denied

次回以降のデプロイ

–guidedオプションでsamconfig.tomlが生成されたので、

次回以降はsamconfig.tomlをデプロイ設定を参照して、デプロイできます。

そのため、次回からは–guidedオプションは必要ありません。

$sam deploy --s3-bucket バケット名 --profile credentialsで設定したプロファイル名

デプロイした内容を削除する

sam delete --s3-bucket バケット名 --profile test スタックネーム
        // 削除の確認が聞かるので、yで承認します。
        Are you sure you want to delete the stack sam-app in the region ap-northeast-1 ? [y/N]: y
        Are you sure you want to delete the folder sam-app in S3 which contains the artifacts? [y/N]: y

        - Deleting S3 object with key sam-app-example/fdc875484a56f2b09ca6b401480dc076
        - Deleting S3 object with key sam-app-example/06e3db2f3105b35e40c60c5e255e1779.template
        - Deleting S3 object with key sam-app-example/319df88a4d6fc83b947d6f2d3bf30954.template
        - Deleting S3 object with key sam-app-example/7a1e4e71cae979172959654ce979edda.template
        - Deleting Cloudformation stack sam-app-example


Deleted successfully
ぎゅう
WEBエンジニア
渋谷でWEBエンジニアとして働く。
LaravelとVue.jsをよく取り扱い、誰でも仕様が伝わるコードを書くことを得意とする。
先輩だろうがプルリクにコメントをして、リファクタしまくる仕様伝わるコード書くマン
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

コメント

コメントする

目次
閉じる