Layer
複数のLambdaから呼ばれる共通モジュールをイメージ。
ディレクトリ構成
common
├── serverless.yml
└── layer
└── python
└── util.py
serverless.yml
service: sample-layer
provider:
name: aws
layers:
samplelayer:
path: layer
util.py
def hello():
print('Hello, Lambda Layers World!')
Lambda Function
上記のLayerモジュールを呼び出すLambda。
ディレクトリ構成
function
├── serverless.yml
└── handler.py
serverless.yml
service: sample-function
provider:
name: aws
runtime: python3.7
iamRoleStatements:
- Effect: "Allow"
Action:
- "lambda:InvokeFunction"
Resource: "*"
functions:
samplefunction:
handler: handler.handle_request
layers:
- {上記のLayerをsls deployした時に表示されるarn}
handler.py
import util
def handle_request(event, context):
util.hello()
実行結果
注意点など
- Layerは
/opt
に展開される。ここにはパスが通っており、Pythonだと/opt/python
と/opt/python/lib/python3.7/site-packages
が使えるので、Layerもpython
ディレクトリを含めたディレクトリ構成にする必要がある。 - デプロイされたLayerの中身はコンソール上で見たり編集したりすることができない。
- Layerはデプロイする度にバージョンが上がり、ARNも変わる。今回の例のように別スタックからARNでLayerを参照する場合は、Layerをデプロイしたら他の参照しているLambdaもデプロイし直す必要がある。