首页 > 解决方案 > SAM 可以创建 s3 存储桶来存储 lambda 函数代码吗?

问题描述

也许这不仅仅是一个问题。尝试注册 SAM Slack 频道,但没有成功。

我正在尝试使用 SAM 构建无服务器应用程序。我习惯于使用 Cloudformation 模板来描述所需的所有资源。现在我很困惑为什么 SAM 的 cli 要求我将 s3 存储桶传递到哪里来上传 lambda 函数代码。我通常希望创建 s3 存储桶(具有随机名称)是 Cloudformation 模板执行的一部分。SAM 是 Cloudformation 的扩展还是不是?

在我的template.yaml我有这样的事情:

Resources:

  SrcBucket:
    Type: AWS::S3::Bucket

  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      Timeout: 3
      Runtime: python3.7
      Handler: my.lambda_handler
      CodeUri: my/
      Events:
        ShopifyInstall:
          Type: Api
          Properties:
            Path: /
            Method: get

如何在 CodeUri 中引用 SrcBucket?

标签: aws-lambdaamazon-cloudformationaws-samaws-sam-cli

解决方案


不幸的是,没有。

SAM 模板的部署分为两部分,一是打包命令,它基本上构建了 zip 文件,需要一个 s3 存储桶来上传。而部署命令就像 cloudformation 一样简单地部署你的打包应用程序。

我通常有一个带有多个 cloudformation 堆栈的小型 bash 脚本,一个是创建此存储桶的帮助程序堆栈(并且还在输出中添加名称),然后获取名称并将其传递给所有其他堆栈

#Create the Helper stack
echo "---------Create Helper stack ---------"
aws cloudformation deploy  --profile ${profile} --stack-name $helperStack -- 
region ${region} --template-file deployment-helper.yaml

serverlessCodeBucketName="$(aws cloudformation --region ${region} --profile 
${profile} describe-stacks --stack-name $helperStack --query 
'Stacks[0].Outputs[?OutputKey==`CodeBucketName`].OutputValue' --output text)"

aws cloudformation package --profile ${profile}  --region ${region} -- 
template-file template.yaml  --output - 
template-file serverless-output.yaml --s3-bucket 
${serverlessCodeBucketName}

aws cloudformation deploy --profile ${profile}  --stack-name 
${applicationStack} --region ${region} --template-file 
serverless-output.yaml --capabilities 
CAPABILITY_IAM 

推荐阅读