amazon-web-services - 使用子堆栈时,Lambda 代码在 `package` 命令期间不会被压缩

标签 amazon-web-services aws-lambda aws-cloudformation

我正在使用 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 规范,HandlerRuntime 键值中不需要引号,
  • PackageType 可以省略。

关于amazon-web-services - 使用子堆栈时,Lambda 代码在 `package` 命令期间不会被压缩,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74171976/

相关文章:

aws-lambda - 使用 API 发送电子邮件时将文件附加到电子邮件

amazon-web-services - 遇到不受支持的属性 SecurityGroupId

amazon-web-services - 将现有 AWS CloudWatch 警报导出到 CloudFormation 模板

amazon-web-services - 如何对上传到 AWS S3 的文件执行自动病毒扫描

amazon-web-services - AWS IAM CLI 标签用户

amazon-web-services - Go & Docker : I'm able to run a go web server when using stdlib, 当我使用自定义包时发生错误

amazon-s3 - 无法使用无服务器框架将图像上传到 s3,但它可以离线工作(缓冲区问题)

amazon-web-services - 删除 X 天内未触及的 AWS 日志组

node.js - 如何在 AWS Lambda 中将消息记录到 Python 中的错误日志

aws-cloudformation - 按照模板中提到的顺序排列参数