My Note

自己理解のためのブログ

APIGateway + Lambda + Go(Echo)をSAM(Serverless Application Model)でAWSとローカルにデプロイする

はじめに

前回、APIGW + Lambda + Go(Echo)のローカル環境をSAMで構築しました。 今回は、samでローカルではなく、AWS環境にデプロイをしました。ローカルも同じ設定で利用可能です。

yhidetoshi.hatenablog.com

本記事ではAWSにデプロイする部分にだけ記載します。詳細は↑の記事に記載済みです。

また、LambdaでGoフレームワークのEchoを動かす事についてまとめた記事は↓。

yhidetoshi.hatenablog.com

コード

ディレクトリ構成

serverless-sam-go-local
├── README.md
└── serverless
    ├── README.md
    ├── echo
    │   ├── Makefile
    │   ├── api
    │   │   └── healthcheck
    │   │       └── healthcheck.go
    │   ├── conf
    │   │   └── config.go
    │   ├── echo
    │   ├── go.mod
    │   ├── go.sum
    │   ├── handler
    │   │   └── auth
    │   │       └── auth.go
    │   └── main.go
    ├── events
    │   └── event.json
    ├── samconfig.toml
    └── template.yaml

ソースコードはこちら。 github.com

APIGWとLambdaの設定

template.yaml

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  description

Globals:
  Function:
    Timeout: 30

Resources:
  MyAPI:
    Type: AWS::Serverless::Api
    Properties:
      Name: sam-echo-test
      StageName: v1
      EndpointConfiguration: REGIONAL
  
  SAMEchoFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: echo
      Handler: echo
      Runtime: go1.x
      Architectures:
        - x86_64
      Events:
        GetApi:
          Type: Api
          Properties:
            Path: /api/{proxy+}
            Method: get
            RestApiId: !Ref MyAPI
            Auth:
              ResourcePolicy:
                CustomStatements: [{
                  "Effect": "Allow",
                  "Principal": "*",
                  "Action": "execute-api:Invoke",
                  "Resource": "arn:aws:execute-api:ap-northeast-1:*:*/*",
                  "Condition": {
                    "IpAddress": {
                      "aws:SourceIp": "X.X.X.X/32"
                    }
                  } 
                }]
      #Environment:
      #  Variables:
      #    PARAM1: VALUE

デプロイ

AWSにデプロイする

初回実行に初期設定が必要なため --guided オプションを付与して、2回目以降の設定反映には不要です。

❯ aws-vault exec my-dev -- sam deploy --guided

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

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

        Setting default arguments for 'sam deploy'
        =========================================
        Stack Name [sam-app]: sam-echo-test
        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]: y
        #Preserves the state of previously provisioned resources when an operation fails
        Disable rollback [y/N]: y
        HelloWorldFunction may not have authorization defined, Is this okay? [y/N]: y
        Save arguments to configuration file [Y/n]: y
        SAM configuration file [samconfig.toml]: 
        SAM configuration environment [default]: dev

        Looking for resources needed for deployment:
        Creating the required resources...
        Successfully created!
(処理の進捗が表示されるので省略)

生成されたsamconfig.tomlの中身は以下のとおりになりました。 スタック名やawsのリソース情報などが記載されています。

  • samconfig.toml
version = 0.1
[dev]
[dev.deploy]
[dev.deploy.parameters]
stack_name = "sam-echo-test"
s3_bucket = "aws-sam-cli-managed-default-samclisourcebucket-xxxxxxxx"
s3_prefix = "sam-echo-test"
region = "ap-northeast-1"
confirm_changeset = true
capabilities = "CAPABILITY_IAM"
disable_rollback = true
image_repositories = []

作成したstackを削除する場合は sam delete コマンドを実行する

  • sam delete を実行するとstack名を問われるので入力する
❯ aws-vault exec my-dev -- sam delete
        Enter stack name you want to delete: sam-echo-test
        Are you sure you want to delete the stack sam-echo-test in the region ap-northeast-1 ? [y/N]: y
        Are you sure you want to delete the folder sam-echo-test in S3 which contains the artifacts? [y/N]: y
        - Deleting S3 object with key sam-echo-test/xxxxxxxx
        - Deleting S3 object with key sam-echo-test/xxxxxxxx.template
        - Deleting Cloudformation stack sam-echo-test

Deleted successfully

awsのAPIGWのエンドポイントに対してAPIコールしてOKを確認

❯ curl https://xxxxxxxxxx.execute-api.ap-northeast-1.amazonaws.com/v1/api/healthcheck
{"status":200,"message":"Success to connect echo"}

ローカルにデプロイする

template.yamlを特に変更せずlocalに展開するコマンドを実行してました。

❯ sam local start-api
Mounting SAMEchoFunction at http://127.0.0.1:3000/api/{proxy+} [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-05 16:44:31  * Running on http://127.0.0.1:3000/ (Press CTRL+C to quit)

動作確認でヘルスチェックAPIを実行してOK

❯ curl http://127.0.0.1:3000/api/healthcheck
{"status":200,"message":"Success to connect echo"}

さいごに

今回、SAMを使ってローカルとAWSにサーバレス環境をデプロイしました。 SAMの機能をまだまだ使いこなせていきたいので他にも試していきたいと思います。