【AWS】Visual Studio CodeでSAMアプリケーション開発

Visual Studio Code(以下vscode)でSAMアプリケーション開発をする手順をまとめます。

前提条件

  • AWS-CLIインストール済み
  • SAM-CLIインストール済み

事前準備

vscodeにAWS Toolkitをセットアップ

  1. vscodeを立ち上げてサイドメニューのEXTENSIONSからAWS Toolkitを検索

  2. AWS Toolkit for Visual Studio Codeをインストール

    サイドメニューにAWSボタンが出てくればOK

アプリケーション開発

新規のSAMアプリケーションを作る

  1. サイドメニューのAWSをクリック

  2. 上段メニューから「Create new SAM Application」

  3. Runtimeを選択(せっかくだからPython3.7を選択する)

  4. アプリケーションを配置する場所を選択 (→sam-test-2)

  5. アプリケーションの名前を入力 (→sam-test)

SAMアプリケーションの作成が完了すると、template.yamlが開く

デプロイ設定

template.yaml

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

  Sample SAM Template for sam-test

# 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.lambda_handler
      Runtime: python3.7
      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

sam buildした時とほぼ同じ内容のtemlateができます。

app.pyを開くと、vscodeがpythonに対応していないと警告が出るので、以下をインストールする。

動作確認

pythonをインストール後、再度app.pyを開くと、今度は

Run Locally | Debug Locally | Configure

のボタンが押せるようになります。

ソースコード上ではこんな感じ

import json

Run Locally | Debug Locally | Configure  <-- VSCodeが出すボタン
def lambda_handler(event, context):
    return {
        "statusCode": 200,
        "body": json.dumps({
            "message": "hello world",
            # "location": ip.text.replace("\n", "")
        }),
    }

ローカルでSAMアプリケーションを実行する

Run Locally

Run Locallyを押して実行する。

Preparing to run app.lambda_handler locally...
Building SAM Application...
Build complete.
Starting the SAM Application locally (see Terminal for output)
Running command: sam local invoke awsToolkitSamLocalResource --template /tmp/aws-toolkit-vscode/output/template.yaml --event /tmp/aws-toolkit-vscode/vsctkRuSN7A/event.json --env-vars /tmp/aws-toolkit-vscode/env-vars.json
Invoking app.lambda_handler (python3.7)
Found credentials in shared credentials file: ~/.aws/credentials

Fetching lambci/lambda:python3.7 Docker container image.............................................................................
Mounting /tmp/aws-toolkit-vscode/vsctkRuSN7A/output/awsToolkitSamLocalResource as /var/task:ro,delegated inside runtime container
START RequestId: xxxxx-xxxxx Version: $LATEST
END RequestId: xxxxx-xxxxx
REPORT RequestId: xxxxx-xxxxx   Duration: 6.29 ms   Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 22 MB  [0m
{"statusCode":200,"body":"{\"message\": \"hello world\"}"}
Local invoke of SAM Application has ended.

デプロイ

SAMアプリケーションをデプロイする

  1. デプロイの前に接続先のAWSをprofileから選択

    上段メニューの「Connect to AWS」 profileの一覧が出るので任意のprofileを選択する

    ~/.aws/credentialsに登録している、access_keyとsecret_keyのセット

  2. 上段メニューのDeploy SAM Application

  3. デプロイ対象のtemplate.yamlを選択する

  4. regionを選択

  5. パッケージングのS3バケットを入力

  6. スタック名を入力

vscode下段のOutputタブにデプロイのログが出力されます。

Starting SAM Application deployment...
Building SAM Application...
Packaging SAM Application to S3 Bucket: test-bucket with profile: sandbox
Deploying SAM Application to CloudFormation Stack: sam-test-2 with profile: sandbox
Successfully deployed SAM Application to CloudFormation Stack: sam-test-2 with profile: sandbox

これを見ると build → packaging → deploy の一連の作業を行ってくれているのが分かります。

※確認手順は前の記事でやった方法と同じ

エラー等

Connect to AWSにcredentialsがうまく反映されないときは

※追加したばかりのprofileはAWS Toolkitを再配置してやらないと反映されません。

サイドメニューのExtensionsからAWS Toolkit for Visual Studio Codeを探してReloadしてやるとよいかもしれません。

実行エラーやデプロイエラーの時は

以下の辺りを確認すると良いかも

  • vscode下段AWS ToolkitをAWS Toolkit Logsに切り替えると詳細なログを確認できる

  • また、SAM-CLIコマンドで --debug オプションつけるとより詳細な情報が見れるので、ここは適時使い分けると良い

  • さらに「CloudFormationまで行ってるのに、Lambda関数が登録されない!」なんてケースもある その場合はAWSコンソールから
    CloudFormationを開き、該当スタックの出力を確認すると何か分かるかも...
    CloudFormationは他チームのスタックもあるのでくれぐれも慎重に操作する

コメント

このブログの人気の投稿

docker-compose up で proxyconnect tcp: dial tcp: lookup proxy.example.com: no such host

docker-compose で起動したweb、MySQLに接続できない事象

【PHP】PHP_CodeSnifferを使う(コーディングルールのカスタマイズ)