我正在尝试构建CF模板,以部署由多个Lambda组成的无服务器系统。就我而言,Lambda资源描述具有很多属性;唯一的区别是文件名和处理函数。
如何在模板中定义类似通用的参数集?
此样板太糟糕了:
LambdaCreateUser:
Type: AWS::Lambda::Function
Properties:
Code:
S3Bucket:
Ref: BucketForLambdas
S3Key: create_user.zip
Handler: create_user.lambda_handler
Runtime: python3.7
Role:
Fn::GetAtt: [ LambdaRole , "Arn" ]
Environment:
Variables: { "EnvTable": !Ref EnvironmentTable, "UsersTable": !Ref UsersTable }
LambdaDeleteUser:
Type: AWS::Lambda::Function
Properties:
Code:
S3Bucket:
Ref: BucketForLambdas
S3Key: delete_user.zip
Handler: delete_user.lambda_handler
Runtime: python3.7
Role:
Fn::GetAtt: [ LambdaRole , "Arn" ]
Environment:
Variables: { "EnvTable": !Ref EnvironmentTable, "UsersTable": !Ref UsersTable }
您正在寻找的是AWS SAM,它是CloudFormation之上的一层语法糖。使用AWS SAM的模板的基本表示如下所示:
AWSTemplateFormatVersion: '2010-09-09'
Transform: 'AWS::Serverless-2016-10-31'
Globals:
Function:
Runtime: python3.7
Environment:
Variables:
EnvTable: !Ref EnvironmentTable
UsersTable: !Ref UsersTable
Resources:
LambdaCreateUser:
Type: AWS::Serverless::Function
Properties:
Code:
S3Bucket:
Ref: BucketForLambdas
S3Key: create_user.zip
Handler: create_user.lambda_handler
Role: !GetAtt LambdaRole.Arn
LambdaDeleteUser:
Type: AWS::Serverless::Function
Properties:
Code:
S3Bucket:
Ref: BucketForLambdas
S3Key: delete_user.zip
Handler: delete_user.lambda_handler
Role: !GetAtt LambdaRole.Arn
但这还不是终点。您可以将代码定义替换为代码甚至内联代码的路径,并使用sam build
和sam package
来构建和上传工件。您也可以用SAM policy templates替换角色定义,以进一步减少样板代码。