AWS SAM CLI 在构建、打包和部署期间忽略我的 Python 依赖项

Tre*_*van 7 amazon-web-services aws-lambda

我正在尝试使用 SAM CLI 工具从 MacOS 部署 AWS Lambda 函数,而不是使用 Docker 容器。

  • SAM CLI 版本 0.4.0
  • Lambda 函数的 Python 3.8 运行时
  • 在 MacOS 上本地安装 Python 3.7
  • 我有一个requirements.txt文件,与我的 Lambda 函数文件位于同一目录中

需求.txt

boto3
botostubs
Run Code Online (Sandbox Code Playgroud)

部署脚本 (PowerShell)

sam build --template-file $InputTemplate
sam package --region $AWSRegion --template-file $InputTemplate --profile $ProfileName --s3-bucket $BucketName --output-template-file $OutputTemplate
sam deploy --region $AWSRegion --profile $ProfileName --template-file $OutputTemplate --stack-name $StackName --capabilities CAPABILITY_NAMED_IAM
Run Code Online (Sandbox Code Playgroud)

实际行为

SAM CLI 忽略我的requirements.txt文件,只部署我的源代码。当我测试我的函数时,这会导致以下错误。

{
  "errorMessage": "Unable to import module 'xxxxxxxxxxxxxx': No module named 'botostubs'",
  "errorType": "Runtime.ImportModuleError"
}
Run Code Online (Sandbox Code Playgroud)

预期行为

SAM CLI 将声明的 Python 依赖项requirements.txt与我的源代码打包在一起。

问题:如何确保 SAM CLI 下载并打包我的 Python 依赖项以及我的源代码?据我所知,我遵循了文档。

https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-using-build.html

Tre*_*van 11

刚刚弄清楚,sam build更深入地阅读该命令。我没有意识到它正在创建一个名为的子文件夹.aws-sam/build/并将修改后的模板存储在那里。

我更新了我的命令和路径,现在它工作得很好。

$InputTemplate = "$PSScriptRoot/cloudformation.yml"
$BuiltTemplate = "$PSScriptRoot/.aws-sam/build/template.yaml"
$BucketName = 'xxxxxxx'
$AWSRegion = 'xxxxxx'
$StackName = 'xxxxxx'

# Package and deploy the application
sam build --template-file $InputTemplate
sam package --region $AWSRegion --template-file $BuiltTemplate --profile $ProfileName --s3-bucket $BucketName
sam deploy --region $AWSRegion --profile $ProfileName --template-file $BuiltTemplate --stack-name $StackName --capabilities CAPABILITY_NAMED_IAM --s3-bucket $BucketName
Run Code Online (Sandbox Code Playgroud)

  • 停止发送 --template-file 到 sam 包和 sam 部署。它将自动使用构建目录中的那个。 (7认同)

Ale*_*981 11

我遇到了类似的问题,失败的根本原因是我指定了 --template-file template.yml。根据此问题https://github.com/awslabs/aws-sam-cli/issues/1252 SAM CLI 查找我的 template.yml 中指定的代码 uri 并仅上传函数代码。

所以我的解决方案是:

  1. sam build中指定--template-file
  2. 运行不带--template-file选项的sam deploy