AWS SAM 生成的 buildspec 中使用的变量都是从 CloudFormation stack 中传递的参数获取的。因此,在创建 AWS SAM 应用程序时,需要使用以下示例代码定义 CloudFormation 模板,其中包括 S3_BUCKET 参数的定义和传递:
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Parameters:
S3_BUCKET:
Type: String
Description: S3 bucket name
Resources:
HelloWorldFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: hello_world/
Handler: app.lambda_handler
Runtime: python3.7
Events:
HelloWorld:
Type: Api
Properties:
Path: /hello
Method: get
Environment:
Variables:
S3_BUCKET: !Ref S3_BUCKET
在这个定义中,S3_BUCKET 参数用于定义要在 AWS SAM 应用程序中使用的 S3 存储桶名称。然后,通过在 buildspec.yml 文件中引用该参数来使用它:
version: 0.2
phases:
install:
runtime-versions:
nodejs: 10
build:
commands:
- echo Building the Lambda function code...
- npm install
- npm run build
post_build:
commands:
- echo Deploying the Lambda function code to S3 bucket: $S3_BUCKET
- aws s3 cp dist s3://$S3_BUCKET/ --recursive
artifacts:
files:
- template.yaml
- packaged.yaml
在 buildspec 文件中,S3_BUCKET 参数来自于 CloudFormation stack 中的定义。通过在 buildspec 文件中使用 $S3_BUCKET 占位符来替换值,并使用 aws s3 命令将构建代码复制到该存储桶。
上一篇:AWSSAMServerless应用发布失败(缺少元数据,但模板已填充)
下一篇:AWSSAM是否可以通过Fn::ImportValue函数向现有的导入的APIGateway资源添加新的无服务器函数?