AWS Lambda部署后Python包pytest无法找到问题排查
我的操作步骤
- 通过
sam init --runtime <runtime> --name <project-name>创建AWS标准的hello_world示例代码 - 将
pytest添加到requirements.txt中,并在app.py里加入了import pytest语句 - 执行命令
sam build --template-file template.yaml && sam deploy --template-file template.yaml --config-env dev --profile awsprofile完成构建和部署
遇到的问题
在AWS上运行函数时,导入 pytest 失败,提示该包不存在。
备注
- 本地的
.aws-sam/build文件夹中已包含pytest包,符合预期。
可能的原因及解决方向
部署未使用构建后的模板
你在sam deploy时指定了原始的template.yaml,而非构建后生成的.aws-sam/build/template.yaml。原始模板没有包含构建好的依赖包路径配置,Lambda无法加载到pytest。
解决:将sam deploy的--template-file参数改为.aws-sam/build/template.yaml,或直接省略该参数,SAM会默认使用构建后的模板。构建环境与Lambda运行时不匹配
若本地构建环境(操作系统、Python版本)和Lambda运行时不一致,会导致依赖包兼容性问题。比如本地用Windows构建,Lambda是Linux环境,即使build文件夹里有pytest,部署后也无法识别。
解决:使用sam build --use-container参数在容器中构建,确保依赖包适配Lambda环境:sam build --template-file template.yaml --use-container && sam deploy --config-env dev --profile awsprofilepytest版本与Lambda运行时不兼容
requirements.txt中未指定pytest版本,可能安装了与Lambda运行时不兼容的版本,导致部署后无法正常导入。
解决:在requirements.txt中指定兼容的pytest版本,比如pytest==7.4.0(根据你的Python运行时选择对应版本),重新构建部署。SAM构建过程存在静默错误
构建时可能出现未提示的错误,导致依赖包未完整打包到部署包中。
解决:删除.aws-sam文件夹,重新执行sam build,查看构建日志确认是否有报错,确保依赖包正常安装。
内容的提问来源于stack exchange,提问作者DarkTrick

