如何在AWS CloudFormation模板中提取常用行?

时间:2018-10-02 16:26:30

标签: amazon-web-services amazon-cloudformation

我有一个模板,我发现有很多重复的行。

GetStatusLambda:
Type: AWS::Lambda::Function
Properties:
  Code:
    S3Bucket: test-deployments
    S3Key:
      Fn::Join: [ "/", [
        test-lambdas,
        Ref: FileNameParameter
      ]]
  Handler: 'test.lambdasEntryPoint::getStatus'
  Runtime: java8
  MemorySize : 512
  Role:
    Fn::GetAtt: [LambdaRole, Arn]
  Description: Lambda attached to get status API
  Timeout: 30

SubmitInformationLambda:
    Type: AWS::Lambda::Function
    Properties:
      Code:
        S3Bucket: test-deployments
        S3Key:
          Fn::Join: [ "/", [
            test-lambdas,
            Ref: FileNameParameter
          ]]
      Handler: 'test.lambdasEntryPoint::submitInformation'
      Runtime: java8
      MemorySize: 512
      Role:
        Fn::GetAtt: [LambdaRole, Arn]
      Description: Lambda attached to Submit Information API
      Timeout: 30

是否可以提取代码,运行时,MemorySize,超时等重复节,并使用Fn:Sub或Fn:GetAtt调用它们?

3 个答案:

答案 0 :(得分:0)

CloudFormation tempates的详细信息是众所周知的,有点难过,但在很大程度上是不可避免的。不幸的是,减少重复的唯一方法是使用嵌套堆栈或某种形式的预处理。您可以使用IDE或构建管道在本地进行预处理,也可以使用Custom Transforms将模板上传到AWS之后。

现在至少可以用YAM1编写CloudFormation模板;在September 2016之前,它们必须用JSON编写,这使它们甚至更加冗长...

答案 1 :(得分:0)

您不能复制或引用块,但可以使用Parameters部分来定义变量,然后在Resources部分中使用它们。但是,请谨慎尝试,因为这样做会使您的CloudFormation模板难以阅读和维护。

Parameters:
  MemorySizeParameter:
    Type: String
    Default: 512
    Description: Memory size in MB

在“资源”部分中使用以下行:

MemorySize:
   Ref: MemorySizeParameter

答案 2 :(得分:0)

ChipGroup

lambda-partials.yaml文件将包含:

  GetStatusLambda:
    Type: AWS::Lambda::Function
    Properties:
      Handler: 'test.lambdasEntryPoint::getStatus'
      Role:
        Fn::GetAtt: [LambdaRole, Arn]
      Description: Lambda attached to get status API
      Fn::Transform:
        Name: "AWS::Include"
        Parameters:
          Location: "s3://somebucket/include-partials/lambda-partials.yaml"
  SubmitInformationLambda:
    Type: AWS::Lambda::Function
    Properties:
      Handler: 'test.lambdasEntryPoint::submitInformation'
      Role:
        Fn::GetAtt: [LambdaRole, Arn]
      Description: Lambda attached to Submit Information API
      Fn::Transform:
        Name: "AWS::Include"
        Parameters:
          Location: "s3://somebucket/include-partials/lambda-partials.yaml"