
使用 AWS SAM 部署 Lambda 函数时,若通过 sam deploy --template-file 显式指定模板文件,会导致依赖包(如 requirements.txt 中声明的 pytest)未被正确打包上传,从而在运行时抛出 ModuleNotFoundError。根本原因在于该参数绕过了 SAM 的自动构建产物引用机制。
使用 aws sam 部署 lambda 函数时,若通过 `sam deploy --template-file` 显式指定模板文件,会导致依赖包(如 requirements.txt 中声明的 pytest)未被正确打包上传,从而在运行时抛出 `modulenotfounderror`。根本原因在于该参数绕过了 sam 的自动构建产物引用机制。
在基于 AWS SAM 构建和部署 Python Lambda 函数时,一个常见但容易被忽视的陷阱是:显式传递 --template-file 参数给 sam deploy 命令,会中断 SAM 对构建产物(.aws-sam/build/)的自动识别与注入流程。即使你已成功执行 sam build 并确认 pytest 等依赖已正确安装到本地构建目录中,sam deploy --template-file template.yaml 仍会跳过对构建后资源的引用,转而直接读取原始模板(即未包含 vendor 包的源 template.yaml),最终导致 Lambda 运行环境缺少所需模块。
✅ 正确做法是:仅在 sam build 阶段指定 --template-file,而在 sam deploy 阶段完全省略该参数。SAM 会自动从默认构建输出路径(.aws-sam/build/template.yaml)加载已注入依赖的更新后模板:
# ✅ 正确:build 指定模板,deploy 由 SAM 自动选择构建后的模板 sam build --template-file template.yaml sam deploy --config-env dev --profile awsprofile
⚠️ 注意事项:
- sam deploy 默认查找并使用 .aws-sam/build/template.yaml —— 这是 sam build 执行后生成的、已将 requirements.txt 中所有依赖打包进函数代码目录的增强版模板;
- 若强制用 --template-file template.yaml,SAM 将忽略构建产物,回退到原始模板,导致部署的仍是“空依赖”的函数代码;
- 可通过检查 .aws-sam/build/
/ 目录确认依赖是否已解压(例如是否存在 pytest/ 子目录及 pytest/__init__.py); - 如需统一配置,建议在 samconfig.toml 中声明 template = "template.yaml",后续所有 sam build 和 sam deploy 均无需重复指定,提升可维护性。
? 补充建议:
pytest 本身并不适合在 Lambda 运行时环境中直接导入(它属于开发/测试工具,非运行时依赖)。生产函数应避免引入此类包;若仅为本地单元测试,请确保 pytest 仅出现在 requirements-dev.txt 中,并在 sam build 时通过 --use-container 或自定义构建脚本排除——真正上线的 requirements.txt 应只包含运行时必需的轻量级依赖(如 requests, boto3 等)。这既是最佳实践,也能显著减小部署包体积、缩短冷启动时间。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!











