如何使用CDK为python运行时创建自定义Lambda层?
Javascript代码,用于定义lambda层和函数:
this.sharedLayer = new lambda.LayerVersion(this, 'shared-layer', {
code: lambda.Code.fromAsset('./lambda-functions/shared-layer'),
compatibleRuntimes: [lambda.Runtime.PYTHON_3_8],
layerVersionName: 'shared-layer',
})
}
this.testFunction = new lambda.Function(this, 'TestFunction', {
runtime: lambda.Runtime.PYTHON_3_8,
handler: 'function.lambda_handler',
code: lambda.Code.fromAsset('./lambda-functions/test'),
layers: [this.sharedLayer]
})
实际的Lambda函数包含共享层文件夹中.py文件的直接导入,如下所示:
import my_shared_functions
./lambda-函数/共享层中的Python层文件夹包含:
/---lambda-functions/
/---shared-layer/
boto3/
my_shared_functions.py
...etc
生成模板文件:
cdk synth --no-staging my-lambda-stack > template.yml
使用SAM在本地构建和测试:
sam build TestFunction && sam local invoke --profile siri-dev HeartbeatFunction
错误:
"Unable to import module 'function': No module named 'my_shared_functions'"
发布于 2022-07-21 03:42:24
将lambda层放入子文件夹'python‘解决了这个问题:
/---lambda-functions/
/---shared-layer/
/---python/
boto3/
my_shared_functions.py
...etc
我运行的假设是CDK的文件夹结构与手动上传图层有一定的不同。
发布于 2022-07-21 04:54:46
如果您正在使用CDK V2,请使用@aws/包。使用这个包可以更容易地管理python依赖项。
请检查下面的代码,使用引擎盖下的对接容器来创建包。
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as pylambda from "@aws-cdk/aws-lambda-python-alpha";
const layerForCommonCode = new pylambda.PythonLayerVersion(
this,
"python-lambda-layer-for-common",
{
layerVersionName: "python-lambda-layer-for-common",
entry: "../lambda-source/common-layer",
compatibleRuntimes: [lambda.Runtime.PYTHON_3_9],
}
);
The lambda-source structure as follows
--lambda-source
--common-layer
--requirements.txt
commonfiles.py
https://stackoverflow.com/questions/73060461
复制相似问题