ひとつのLambdaで複数のLambda Layersを使っているとき、ふと気になったんです。 「それぞれのLambda Layersに同じ名前のフォルダがあったらどうなるんだろう?」と。
├── layers1
│ └── hello
│ └── hello_layers1.py
└── layers2
└── hello
└── hello_layers2.py
というわけで、試してみました。
おすすめの方
- 複数のLambda Layersに同じ名前のフォルダがある場合の動作を知りたい方
異なるLambda Layersで同じフォルダ名の場合を試してみる
sam init
sam init \
--runtime python3.11 \
--name lambda-layers-same-folder-name-sample \
--app-template hello-world \
--no-tracing \
--no-application-insights \
--structured-logging \
--package-type Zip
Lambda Layers
Lambda Layers用のフォルダを作ります。
mkdir -p layers1/hello
mkdir -p layers2/hello
このフォルダに対して、異なる名前のファイルを作成します。
Layersコード(その1)
touch layers1/hello/hello_layers1.py
hello_layers1.py
def hello():
return "hello from layers1"
Layersコード(その2)
touch layers2/hello/hello_layers2.py
hello_layers2.py
def hello():
return "hello from layers2"
Lambdaコード
app.py
import json
from hello import hello_layers1
from hello import hello_layers2
def lambda_handler(event, context):
return {
"statusCode": 200,
"body": json.dumps(
{
"hello1": hello_layers1.hello(),
"hello2": hello_layers2.hello(),
}
),
}
AWS SAMテンプレート
2つのLambda Layersと1つのLambdaをデプロイします。
template.yaml
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: lambda-layers-same-folder-name-sample
Resources:
Hello1Layer:
Type: AWS::Serverless::LayerVersion
Metadata:
BuildMethod: python3.11
Properties:
LayerName: hello1-layer
ContentUri: layers1
CompatibleRuntimes:
- python3.11
Hello2Layer:
Type: AWS::Serverless::LayerVersion
Metadata:
BuildMethod: python3.11
Properties:
LayerName: hello2-layer
ContentUri: layers2
CompatibleRuntimes:
- python3.11
HelloWorldFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: hello_world/
Handler: app.lambda_handler
Timeout: 3
Runtime: python3.11
Architectures:
- x86_64
Layers:
- !Ref Hello1Layer
- !Ref Hello2Layer
Events:
HelloWorld:
Type: Api
Properties:
Path: /hello
Method: get
HelloWorldFunctionLogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub /aws/lambda/${HelloWorldFunction}
デプロイ
sam build --use-container
sam deploy \
--guided \
--region ap-northeast-1 \
--stack-name lambda-layers-same-folder-name-sample-stack
APIを呼ぶと、それぞれのファイルが参照できていた
$ curl https://xxx.execute-api.ap-northeast-1.amazonaws.com/Prod/hello
{"hello1": "hello from layers1", "hello2": "hello from layers2"}
おまけ: 異なるLambda Layersで同じフォルダ名&同じファイル名の場合を試してみる
同じファイル名の場合は、片方のファイルのみが参照されました。
$ curl https://xxx.execute-api.ap-northeast-1.amazonaws.com/Prod/hello
{"hello1": "hello from layers2", "hello2": "hello from layers2"}
同じファイル名にする
mv layers1/hello/hello_layers1.py layers1/hello/hello_layers.py
mv layers2/hello/hello_layers2.py layers2/hello/hello_layers.py
Lambdaコード
app.py
import json
from hello import hello_layers
from hello import hello_layers
def lambda_handler(event, context):
return {
"statusCode": 200,
"body": json.dumps(
{
"hello1": hello_layers.hello(),
"hello2": hello_layers.hello(),
}
),
}