CloudFormation 模板:减少样板代码

CloudFormation template: reduce boilerplate code

我正在尝试编写 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 buildsam package 来构建和上传您的工件。您还可以将角色定义替换为 SAM policy templates 以进一步减少样板代码。