我正在使用 CloudFormation 创建 lambda 函数。 lambda 函数存储在单独的文件中,然后使用 aws cloudformation package
命令重新创建。这工作正常并且堆栈部署成功:
# Filename: auth/auth.yml
# Lambda JS file: auth/lambda-pre-signup.js
Resources:
## Other resources here
MyPreSignupLambda:
Type: AWS::Lambda::Function
Properties:
Architectures:
- arm64
Code: 'lambda-pre-signup.js'
Handler: 'lambda-pre-signup.handler'
Runtime: nodejs16.x
PackageType: Zip
Role: !GetAtt MyRole.Arn
命令:
aws cloudformation package --template-file auth.yml --s3-bucket my-bucket --output-template-file generated-auth.yml
aws cloudformation deploy --template-file generated-auth.yml --stack-name test-stack --capabilities CAPABILITY_IAM
但是,当我创建根堆栈模板并引用 lambda 时,出现错误:
Resource handler returned message: "Could not unzip uploaded file. Please check your file, then try to upload again. (Service: Lambda, Status Code: 400, Request ID: xxxxx)"
当我检查S3存储桶中是否有上传的文件时,源代码在那里,但未压缩(我可以下载并直接查看代码,无需解压)。
这是我当前的根堆栈 CF 模板:
# Filename: root.yml
Resources:
MyAuth:
Type: AWS::CloudFormation::Stack
Properties:
TemplateURL: ./auth/auth.yml
命令:
aws cloudformation package --template-file root.yml --s3-bucket my-bucket --output-template-file generated-root.yml
aws cloudformation deploy --template-file generated-root.yml --stack-name test-root-stack --capabilities CAPABILITY_IAM
package
命令中是否有某些选项可确保上传的 lambda 代码已压缩?
编辑:写了一个错误的论点
最佳答案
官方AWS CLI documentation明确指出:
If you specify a file, the command directly uploads it to the S3 bucket. If you specify a folder, the command zips the folder and then uploads the .zip file.
为了确保您的文件被压缩,您可以创建一个新目录(例如 code
)并将您的 lambda-pre-signup.js
文件放在那里:
mkdir code
mv lambda-pre-signup.js code/
那么您更正后的 CloudFormation 模板可能如下所示:
# Filename: auth/auth.yml
# Lambda JS file: auth/code/lambda-pre-signup.js
Resources:
# Other resources here
MyPreSignupLambda:
Type: AWS::Lambda::Function
Properties:
Architectures:
- arm64
Code: code/
Handler: lambda-pre-signup.handler
Runtime: nodejs16.x
Role: !GetAtt MyRole.Arn
旁注:
- 我使用了
code/
来明确指示目录,code
也应该可以工作, - 根据 YAML 规范,
Handler
和Runtime
键值中不需要引号, PackageType
可以省略。
关于amazon-web-services - 使用子堆栈时,Lambda 代码在 `package` 命令期间不会被压缩,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74171976/