Upgrade to Pro — share decks privately, control downloads, hide ads and more …

AWS Serverless Application Model入門_20250708

AWS Serverless Application Model入門_20250708

AWS Serverless Application Modelの入門者レクチャを実施した際の記事です。

Avatar for ShinMatsuzaki

ShinMatsuzaki

August 06, 2025
Tweet

More Decks by ShinMatsuzaki

Other Decks in Programming

Transcript

  1. AWS Serverless Application Model(SAM) の概要 • AWS上でサーバーレスアプリケーションを構築するための OSSなCLIツール ◦ https://github.com/aws/aws-sam-cli

    • 主要な機能 ◦ IaC : YAML / TOML形式で、インフラ定義を書くことができる ◦ Build & Deploy : IaC + アプリケーションコードのビルド&デプロイ機能
  2. 実際に動かしてみる sam-python $ sam init 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 - GraphQLApi Hello World Example 11 - Full Stack 12 - Lambda EFS example 13 - Serverless Connector Hello World Example 14 - Multi-step workflow with Connectors 15 - DynamoDB Example 16 - Machine Learning Template: 1 プリセットのテンプレート or カスタムテンプレート プリセットなテンプレート の一覧
  3. 実際に動かしてみる sam-python $ sam init Use the most popular runtime

    and package type? (python3.13 and zip) [y/N]: y Would you like to enable X-Ray tracing on the function(s) in your application? [y/N]: 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]: N Would you like to set Structured Logging in JSON format on your Lambda functions? [y/N]: y Structured Logging in JSON format might incur an additional cost. View https://docs.aws.amazon.com/lambda/latest/dg/monitoring-cloudwatchlogs.html#monitoring-cloudwatchlogs-pricing for more details Project name [sam-app]: sam-python ----------------------- Generating application: ----------------------- Name: sam-python Runtime: python3.13 Architectures: x86_64 Dependency Manager: pip Application Template: hello-world Output Directory: . Configuration file: sam-python/samconfig.toml Next steps can be found in the README file at sam-python/README.md Commands you can use next ========================= [*] Create pipeline: cd sam-python && sam pipeline init --bootstrap [*] Validate SAM template: cd sam-python && sam validate [*] Test Function in the Cloud: cd sam-python && sam sync --stack-name {stack-name} --watch 構造化ログは便利 なのでONにする ことが多い 分散トレーシング。使わな いことが多い。 Application Insightsは、パ フォーマンスにシビアなラムダ 関数なら導入を検討してもいい かも
  4. 実際に動かしてみる sam-python $ cd sam-pyth sam-python $ tree -L 2

    . ├── .gitignore ├── README.md ├── __init__.py │ ├── events │ └── event.json │ ├── hello_world │ ├── __init__.py │ ├── app.py │ └── requirements.txt │ ├── samconfig.toml ├── template.yaml └── tests ├── __init__.py ├── integration ├── requirements.txt └── unit Python Code IaCファイル Python Code
  5. 基本的な操作 # Validate & Lint $ sam validate --lint /home/matsuzaki/work/sam-python/sam-python/template.yaml

    is a valid SAM Template # Build $ sam build --use-container # Deploy $ sam deploy --debug 開発環境の構成をDockerに閉じ込め、共通化できるのでおすすめ --debugを付与した方が、動きが理解しやすくトラブルシュートも容易 # ローカル環境でのDockerを使ったラムダ関数の実行 $ sam local invoke # イベントオブジェクトを使った動作確認 $ sam local invoke -e ./events/event.json
  6. 参考:イベントドリブンモデル イベントソース AWS Lambda ランタイム ラムダ関数内の handler定義 event object event

    object Cloud Watch Logs Lambda プログラミングモデルの概要  ・ランタイムは、呼び出しイベント、および関数名やリクエスト ID などの   コンテキストを含むオブジェクトをハンドラーに渡す。   ・ランタイムは、関数からのログ出力をキャプチャし、    Amazon CloudWatch Logs に送信する ランタイムの役割のより解像度の高い理解に際しては、以下が詳しい。 AWS Lambda handler はどのように呼ばれるのか context object
  7. アプリケーション側の操作 $ uv run --with-requirements tests/requirements.txt python -m pytest tests/unit

    -v ======================================== test session starts ========================================= platform linux -- Python 3.10.12, pytest-8.4.1, pluggy-1.6.0 -- /home/matsuzaki/work/sam-python/sam-python/.venv/bin/python cachedir: .pytest_cache rootdir: /home/matsuzaki/work/sam-python/sam-python collected 1 item tests/unit/test_handler.py::test_lambda_handler PASSED [100%] ========================================= 1 passed in 0.02s ========================================== lint - 文法とコードスタイルのチェック Unit Testの実行
  8. CodeUri と Handler と EntryPoints Resources: HelloWorldFunction : Type: AWS::Serverless::Function

    Properties : CodeUri: hello-world/ Handler: app.lambdaHandler Runtime: nodejs22.x Architectures: - x86_64 Metadata: BuildMethod: esbuild BuildProperties : Minify: true Target: "es2020" Sourcemap: true EntryPoints: - app.ts 補足: Handlerは「拡張子を除いたファイル名」. 「Handler関数名」で書く。 ※コード内の関数名と合わせること。 EntryPointsは、「拡張子を含めたファイル名」 を書けばOK。 sam build 実行時のビルドコンテキスト(起 点)となるディレクトリのパスを指定 Handler -> ラムダ関数実行時の実行対象とする ファイル名+関数名 EntryPoints -> sam build実行時に、CodeUriと 一緒に、ビルド対象のファイルを解決するために 使われる
  9. template.yamlに書く、 Handlerの関数名はtemplate.yamlの定義と合わせる必要がある export const lambdaHandler = async (event: APIGatewayProxyEvent ):

    Promise<APIGatewayProxyResult > => {}; 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.lambdaHandler Runtime: nodejs22.x Architectures: - x86_64 ※handler関数の命名は自由。template.yamlのHandlerと整合すればなんでもいい
  10. sam build は何をやっているのか • sam build を実行すると、~/.aws-sam 配下にIaCファイルとプログラムのコードが生成 される ◦

    Typescriptの場合、トランスパイル後の ファイルが格納される • sam deploy実行時には、トップレベルディレク トリ配下のファイルではなく 、これのファイルが 参照される ◦ 従って、変更を反映するためには、 deployの前にbuildが必須となる
  11. Managed default S3 bucket CFn Stack : aws-sam-cli-managed-default S3 Bucket:

    SamCli SourceBucket S3 Bucket Policy ルート CFnスタック名1 CFnのChangeSet CFnスタック名2 CFnのChangeSet S3 Bucket : SamCliSourceBucket • CLIまたは、template.yamlで --resolve-s3 を有効にすると、SAM CLIは以下のような動きをする。 ① 初回実行時に、S3バケット(SamCliSourceBucket)を作成する。 このS3バケットは、以後、共用の CFnファイル置き場として使われる。 ↑sam(1)の 「--resolve-s3」 のhelpに出てくる、 managed default AWS S3 bucketというのはこれ ② --resolve-s3 を有効にした状態で、「 sam deploy」 を実行すると、 SAM CLIはまず、CFn Stack「aws-sam-cli-managed-default」を探しに行き、見 つかると、それに紐づく S3にCFnのチェンジセットを格納する。
  12. TIPS : AWS SAMでS3を管理するのはできるだけ避けた方がよさそう。 推奨: AWS SAM では、S3ファイルを宣言・管理せずに、terraformなどで事前に S3バケットを用意しておき、それをバケット名ベースでアクセスする方式を採用する。 理由:

    1. 内部的な状態(つまり、消えては困るデータ)を持つインフラと、そうではない  ステートレスなラムダ関数、API-GWなどのインフラを、同じIaCファイル内で  同居させるべきではない。必ず、「S3を消したくないから、ラムダ関数と  API-GWが再作成できない」ということが起きる。 2. AWS SAMでS3を管理する場合、DeletionPolicyやUnpdateReplacePolicyを使いたく  なるが、素朴に実装すると、「sam detele→sam deployのタイミングで、  resource already existsでCFnがSAMから操作不能になる」などつらみが多い。 https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-attribute-deletionpolicy.html https://dev.classmethod.jp/articles/cloudformation-updatereplacepolicy/