12
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

概要

以前の記事でFastAPIをLambdaで使用してAPIを設計し、APIGatewayでデプロイするのをCDKで行うというのをあげたのですが、その際にLambdaレイヤーをCDKで作成するのに詰まった点があったのでその部分をとりあげます。

Lambdaレイヤーを作成する準備

FastAPIとMungumをLambdaで使うことを想定する。
レイヤーとなるdependencies.zipを作成する。

使いたい外部ライブラリをまとめたrequirements.txtを作成

requirements.txt
fastapi
mangum

依存関係をzipにまとめる

mkdir python
pip install -r requirements.txt -t python/python/lib/python3.10/site-packages/
cd python
zip -r ../dependencies.zip .
cd ..
rm -rf python

最初に作成したPythonファイルは一時的にインストールしたライブラリ置いておくためのものであるため、最後に削除のコマンドを入れている。
もし必要であればpackage.jsonにこれらのコマンドを定義しておいて1コマンドで簡単に実行できるようにしておくといいかもしれない。

レイヤーの中身のファイル構造(python/lib/python3.10/site-packages)は決まっていて、これに沿っていなかったらレイヤーを作成しても中身を認識してくれない。(公式ガイド参照)

CDKでlambdaとレイヤーを作成して関連づける

    ...

    // レイヤー作成
    const layer = new lambda.LayerVersion(this, "CustomLayer", {
      // レイヤーzipファイルのパスを指定
      code: lambda.Code.fromAsset("dependencies.zip"),
      compatibleRuntimes: [lambda.Runtime.PYTHON_3_10],
      description: "A layer to hold the FastAPI and Mangum dependencies",
    });

    // Lambda関数の作成
    const fn = new lambda.Function(this, "handler", {
      runtime: lambda.Runtime.PYTHON_3_10,
      handler: "app.handler",
      code: lambda.Code.fromAsset(path.join(__dirname, "../lambda")),
      layers: [layer], // ここでレイヤーを関数に追加
    });

    ...

レイヤー作成自動化

レイヤーzipを作成した以下のコマンド部分を自動化した方がいいかもしれないと思った。

mkdir python
pip install -r requirements.txt -t python/python/lib/python3.10/site-packages/
cd python
zip -r ../dependencies.zip .
cd ..
rm -rf python

CDKにはpackage.jsonというファイルがあり、ここでコマンドを定義することができるのでこれを使う。

package.json
{
    ...
    "scripts": {
        "build": "tsc",
        "watch": "tsc -w",
        "test": "jest",
        "cdk": "cdk",
        "layer": "mkdir python && pip install -r requirements.txt -t python/python/lib/python3.10/site-packages/ && cd python && zip -r ../dependencies.zip . && cd .. && rm -rf python"
      },
    ...

"script"に上記の"layer"のようにコマンドを設定できる。名前はlayerでもなんでもいい。

実行する方法は、

npm run layer

となる。これをcdk deployの前に実行すれば良い。

まとめ

CDKでLambdaレイヤーを実装する方法についてまとめました。
Lambdaに必要な外部ライブラリはローカルにインストールしていても動作しないので、直接ライブラリファイルを含めてデプロイするか、本記事のようにレイヤーを作成するかなどの処理が必要です。

12
2
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
12
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?