1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

AWS Lambdaレイヤー化&自動バージョン管理 ― 作業全体のまとめ

Last updated at Posted at 2025-04-23

AWS Lambda Layer + SAM まとめ

現在進めているプロジェクトにおいて、これまではlambdaのコードを直接いじっていたが、同じ関数を何度も繰り返し利用する場面とコードの更新の際に全ての関数を開き、モジュール化しているコードを修正しなければならなかった。今回、AWS SAMを利用することで、モジュールのレイヤー化及びその環境変数やバージョン管理を一括に行う。
この記事は、MySQL 接続ユーティリティを共通コードとして Lambda Layer 化し、AWS SAM を使って 自動バージョン管理&全関数反映を行う手順の備忘録である。
SAMを用いることによってレイヤーの一元管理が可能となり、レイヤー機能の更新の際にすべての任意のレイヤーを使用しているすべての関数に対してバージョンアップが可能になる。


目的

  • 必要な Python ライブラリを Layer にまとめる
  • sam build && sam deploy のみで Layer の新バージョン発行 → すべての関数に即時反映

開発環境

  • Python: 3.11.x
  • AWS CLI: v2
  • SAM CLI: 1.x
  • (任意)Docker: ビルドにコンテナを使う場合

実装手順

プロジェクト構成

CONNECTRAYER/
├── common_layer/ ← Layer 用ディレクトリ
│ └── python/
│ ├── connect_db.py ← 共通モジュール (今回はconnect_db.py)
│ ├── mysql/ … ← pip install -t で展開されたライブラリ
│ └── mysql_connector_python-*.dist-info/
├── db_client/ ← Lambda 関数用フォルダ ここにメイン処理を書き加える
│ ├── lambda_function.py ← Handler 本体
│ └── init.py
├── template.yaml ← SAM テンプレート
└── samconfig.toml ← ガイド付きデプロイ設定


共通モジュール:connect_db.py

# common_layer/python/connect_db.py
import os
import mysql.connector
import logging

logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")

def connect_db(path):
    print("test") #ここにレイヤー処理を書き加えていく
    return 

SAM テンプレート:template.yaml

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: ConnectLayer + DbClientFunction

Globals:
  Function:
    Timeout: 10
    Tracing: Active
    LoggingConfig:
      LogFormat: JSON

Resources:
  ConnectLayer:
    Type: AWS::Serverless::LayerVersion
    Properties:
      LayerName: common-layer
      Description: MySQL 接続ユーティリティ
      ContentUri: common_layer/
      CompatibleRuntimes: [ python3.11 ]
      RetentionPolicy: Delete

  DbClientFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: db_client/
      Handler: lambda_function.lambda_handler
      Runtime: python3.11
      Layers:
        - !Ref ConnectLayer
      Environment:
        Variables:
          DB_HOST:     your-db-host
          DB_USER:     your-user
          DB_PASSWORD: your-password
          DB_NAME:     sampledb
          DB_PORT:     '114514'
      Events:
        ApiInvoke:
          Type: Api
          Properties:
            Path: /hello
            Method: get

Outputs:
  ApiUrl:
    Description: API Gateway URL
    Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello"
  DbClientFunctionArn:
    Description: Lambda ARN
    Value: !GetAtt DbClientFunction.Arn


ビルド & デプロイ

# 共通モジュール修正 → 必要ライブラリ再インストール
pip install mysql-connector-python -t connect_layer/python/

# 一括ビルド & デプロイ
sam build
sam deploy

ローカルテスト

## 単体呼び出し
echo '{}' > events/event.json
sam local invoke DbClientFunction -e events/event.json

# HTTP API をローカル起動
sam local start-api
curl http://127.0.0.1:3000/hello

運用ポイント

  • RetentionPolicy: Delete で古い LayerVersion は自動削除

  • 環境変数は SAM テンプレートで一元管理(Secrets Manager 推奨)

  • CI/CD(GitHub Actions 等)に sam build && sam deploy を組み込む


効果

  • 共通 DB 接続コードを 1 か所 で管理

  • 修正 → sam deploy だけで 全関数に即反映

  • 関数 ZIP が軽量化 → Cold Start 短縮

  • チームでのオンボーディングがスムーズ

メモ

  • 初期セットアップ方法
  • samとは
  • 新しいlambda関数のつくりかた
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?