大田区から発信するゆるゆる日記

主にITエンジニアに関する備忘録日記。たまに趣味も。何か不備があればコメント頂けると幸いです。Twitterアカウント https://twitter.com/ryuzan03

【AWS】SAMでLambda,EFS,RDS,S3,ApiGateway連携アプリケーションを作成(1/2)

※下記の内容に不備がありましたら、コメント頂けると幸いです。また、下記の内容をご使用頂ける場合は自己責任でお願いします。

概要

今回はSAMでLambda,EFS,RDS,S3,ApiGateway連携アプリケーションを作成していきます。

SAMでベースのアプリケーションを作成してから、各リソースとの連携を実装していこうと思います。
少し長くなりそうなので、分割して投稿します。

今回は以下のサイトを参考に、ベースとなるアプリケーションを構築していきます。
チュートリアル Hello World アプリケーションの導入 - AWS Serverless Application Model


SAMでHello World

今回もmacOSで実装していきます。

AWS SAM CLIのインストール

以下のサイトを参考にAWS SAM CLIをインストールします。
インストール方法は本題からブレるので割愛します。
macOS への AWS SAM CLI のインストール - AWS Serverless Application Model

  1. AWS アカウントの作成
  2. IAM アクセス許可の設定
  3. Docker をインストールします。注意 Dockerは、アプリケーションをローカルでテストするための前提条件です。
  4. Homebrew をインストールします。
  5. AWS SAM CLI のインストール


Sampleプロジェクトのベース作成

sam initで簡単にリポジトリのベースを作成することができます。

bash

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

Which runtime would you like to use?
    1 - nodejs12.x
    2 - python3.8
    3 - ruby2.7
    4 - go1.x
    5 - java11
    6 - dotnetcore3.1
    7 - nodejs10.x
    8 - python3.7
    9 - python3.6
    10 - python2.7
    11 - ruby2.5
    12 - java8.al2
    13 - java8
    14 - dotnetcore2.1
Runtime: 2

Project name [sam-app]: sam-app

Cloning app templates from https://github.com/awslabs/aws-sam-cli-app-templates.git

AWS quick start application templates:
    1 - Hello World Example
    2 - EventBridge Hello World
    3 - EventBridge App from scratch (100+ Event Schemas)
    4 - Step Functions Sample App (Stock Trader)
    5 - Elastic File System Sample App
Template selection: 1

-----------------------
Generating application:
-----------------------
Name: sam-app
Runtime: python3.8
Dependency Manager: pip
Application Template: hello-world
Output Directory: .

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


これでsam-appのリポジトリが以下の構成で作成されているはずです。

 sample-sam-app/
   ├── README.md
   ├── events/
   │   └── event.json
   ├── hello_world/
   │   ├── __init__.py
   │   ├── app.py            #Contains your AWS Lambda handler logic.
   │   └── requirements.txt  #Contains any Python dependencies the application requires, used for sam build
   ├── template.yaml         #Contains the AWS SAM template defining your application's AWS resources.
   └── tests/
       └── unit/
           ├── __init__.py
           └── test_handler.py



ビルド

sam-appプロジェクトをビルドするために、sam buildを実行します。
プロジェクトのディレクトリに移動してから実行しましょう。

bash

$ cd sam-app
sam-app $ sam build
Building codeuri: hello_world/ runtime: python3.8 metadata: {} functions: ['HelloWorldFunction']
Running PythonPipBuilder:ResolveDependencies
Running PythonPipBuilder:CopySource

Build Succeeded

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

Commands you can use next
=========================
[*] Invoke Function: sam local invoke
[*] Deploy: sam deploy --guided


ビルドに成功すると、sam-appディレクトリ直下に以下のファイルが作成されます。

.aws-sam/build
.aws-sam/build/template.yaml


sam-appプロジェクトを作成した際に指定したPythonのバージョンの設定を行っていないと、buildでエラーが発生します。その際は別途設定が必要になります。



デプロイ

遂にAWSクラウドにsam-appプロジェクトをデプロイします。
デプロイもとても簡単で、sam deployコマンドを実行するだけです。

今回は初回なので、ガイド付き(--guide, -g)でデプロイしてみます(初回はガイド付きじゃないとsam deployコマンドは実行できないみたい)。

bash

$ sam deploy -g

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

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

        Setting default arguments for 'sam deploy'
        =========================================
        Stack Name [sam-app]: sam-app
        AWS Region [us-east-1]: 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
        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]: 

        Looking for resources needed for deployment: Not found.
        Creating the required resources...
        Successfully created!

                Managed S3 bucket: aws-sam-cli-managed-default-samclisourcebucket-1e3i2
                A different default S3 bucket can be set in 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/1696cfa0a6a173b9162e5a  546199 / 546199.0  (100.00%)

--------------省略--------------

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

これでSAMを使ったデプロイが完了しているはずです。

実際に確かめてみます。
まずはCloudFormationから。 f:id:ryuzan03:20201120103904p:plain
大丈夫そうですね。

次はLambda。 f:id:ryuzan03:20201120103858p:plain
こちらも大丈夫そうです。

他のリソースの確認は割愛しますが、無事にSAMでデプロイができました。

ちなみにSAMでの課金はありませんが、今回立ち上げたリソースの中には放っておくと課金されるものがあります。 今後使用しないような場合はCloudFormationのコンソール画面からスタックを削除しておいて方が良さそうです。
S3バケットは一緒には削除されないようなので、不要であればS3のコンソール画面から削除しておきましょう。


用語集

Amazon EventBridge

参考資料: Amazon EventBridge とは - Amazon EventBridge よくある質問 - Amazon EventBridge | AWS

CloudWatch Eventsを拡張するサービス。CloudWatch Eventsと同じサービスを使える他、独自のアプリケーションとAWSリソースを簡単に接続しデータのやりとりができるようにします。

Scratch

参考資料: Scratch - Imagine, Program, Share

プログラミング言語。子供向けコンテンツの作成に特化しており、子供自身がゲームやアニメーションなどのコンテンツをプログミングすることで、創造的に考える力が身に付くとされている。

template.yaml

参考資料: チュートリアル Hello World アプリケーションの導入 - AWS Serverless Application Model

SAMアプリケーションのAWSリソースを定義するテンプレート。

hello_world/app.py

参考資料: チュートリアル Hello World アプリケーションの導入 - AWS Serverless Application Model

Lambdaハンドラロジック部分。

hello_world/requirements.txt

参考資料: チュートリアル Hello World アプリケーションの導入 - AWS Serverless Application Model

Pythonの依存関係(サードパーティ)が定義されている。アプリケーションの依存関係構築に使用されるので、かなり重要。 Pythonをvendorとするならば、vendor/pythonディレクトリを作成してファイル移動してもいいかも。

samconfig.toml

参考資料: AWS SAM CLI構成ファイル - AWS Serverless Application Model

tomlは設定ファイルを定義するための拡張子です。
AWS AWS CLIでデプロイする時に必要な設定情報が書き込まれるファイルです。
これまた重要。


今後に向けて

次回は本題であるLambda,EFS,RDS,S3,ApiGatewayが連携しているアプリケーションを構築していきます。