
使用 SAM 部署 Lambda 函数时,若在 sam deploy 中显式指定 --template-file 参数,会导致构建阶段生成的依赖(如 requirements.txt 中声明的 pytest)被跳过,从而引发运行时报错“ModuleNotFoundError”。正确做法是仅在 sam build 中指定模板,而让 sam deploy 自动读取构建输出目录中的打包产物。
使用 sam 部署 lambda 函数时,若在 `sam deploy` 中显式指定 `--template-file` 参数,会导致构建阶段生成的依赖(如 `requirements.txt` 中声明的 `pytest`)被跳过,从而引发运行时报错“modulenotfounderror”。正确做法是仅在 `sam build` 中指定模板,而让 `sam deploy` 自动读取构建输出目录中的打包产物。
在 AWS Serverless Application Model(SAM)工作流中,sam build 和 sam deploy 各司其职:
- sam build 负责解析 template.yaml,安装 requirements.txt 中的依赖(如 pytest),并将代码与依赖合并到 .aws-sam/build/ 目录下;
- sam deploy 则默认从该构建目录读取已打包的函数代码和依赖,并上传至 Lambda。
关键陷阱:当你执行
sam deploy --template-file template.yaml --config-env dev --profile awsprofile
SAM 会忽略 .aws-sam/build/ 中的构建产物,转而直接基于原始 template.yaml 重新解析资源定义——但此时并未触发依赖安装逻辑,因此部署包中不包含 pytest 等第三方包,导致 Lambda 运行时导入失败。
✅ 正确命令组合应为:
立即学习“Python免费学习笔记(深入)”;
sam build --template-file template.yaml && \ sam deploy --config-env dev --profile awsprofile
注意:sam deploy 不带 --template-file,它将自动使用 sam build 输出的 .aws-sam/build/template.yaml(已注入层路径、CodeUri 等构建后信息),确保依赖包被完整包含。
? 额外建议:
- 若项目使用 samconfig.toml,可在其中统一配置模板路径,避免重复指定:
[default.deploy.parameters] template = "template.yaml" config_env = "dev" profile = "awsprofile"
此后只需运行 sam build && sam deploy 即可。
- 验证部署包内容:部署前可检查 .aws-sam/build/<FunctionLogicalId>/ 目录是否包含 pytest/ 子目录及 pytest/__init__.py;也可在 Lambda 控制台中下载部署包 ZIP 文件进行本地校验。
- ⚠️ 注意:pytest 本身不适用于生产环境 Lambda 函数(它是测试框架,非运行时依赖)。实际项目中请确保 requirements.txt 仅包含运行必需的包(如 requests, boto3),测试依赖应通过 tests/ 目录隔离或使用 extras_require 定义。
遵循上述流程,即可确保所有 requirements.txt 声明的 Python 包被正确打包并部署至 AWS Lambda。


















