首页 > 解决方案 > 自定义 template.yaml 时,部署的 Lambda 中缺少 aws-sam-cli Python requirements.txt

问题描述

对于同一个项目,我有几个 AWS SAM 模板,其中 lambdas 使用 Python 3.8,部分用于不同的环境,部分用于尝试新事物,我-t my-template.yaml用来指定要使用的模板。

我使用常规构建sam build -t my-template.yaml && sam deploy -t my-template.yaml

问题:requirements.txt 文件似乎在构建步骤中受到尊重,部署步骤似乎被忽略了。

.aws-sam/build/MyFunction包含要求:

$ ls
app.py   
certifi-2020.12.5.dist-info  
chardet-4.0.0.dist-info  
idna-2.10.dist-info  
pymysql                  
rds_config.py  
requests-2.25.1.dist-info  
urllib3
certifi  
chardet                      
idna                     
__init__.py          
PyMySQL-1.0.2.dist-info  
requests       
requirements.txt           
urllib3-1.26.3.dist-info

但是在云中运行时,lambda 失败并出现异常,提示找不到 pymysql,当我在 AWS UI 中检查该函数时,没有包含任何要求(例如,没有 PyMySQL-1.0.2.dist-info) .

我注意到,如果我不使用该-t标志sam deploy而只在其中使用默认template.yaml文件,那么要求似乎已正确包含,并且 lambda 成功运行。

我可能做错了什么?

requirements.txt 内容:

$ cat requirements.txt
requests
pymysql

山姆版本:

$ sam --version
SAM CLI, version 1.18.1

操作系统:

$ cat /etc/os-release 
NAME="Ubuntu"
VERSION="20.04.2 LTS (Focal Fossa)"
....

标签: pythonamazon-web-servicesaws-lambdaaws-sam-cli

解决方案


The solution was to use:

sam build -t my-template.yaml

But then do:

sam deploy

without adding -t my-template.yaml again

Answer from the ticket below:

What you are doing is telling sam deploy to use the "source template" which points to non-built functions. Instead, if you drop the -t from the sam deploy command, SAM CLI will pick up the built template from .aws-sam/build/template.yaml which will have all the dependencies "installed".

https://github.com/aws/serverless-application-model/issues/1927


推荐阅读