0
0

More than 3 years have passed since last update.

Serverlessテンプレートでは, 共通部分はGlobalsにまとめよう

Posted at

こんな感じで, ServerlessのTemplateにリソースを並べていませんか?

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31

# 略

Resources:
  SampleFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: app/
      Handler: app.sample
      Role: !Ref RoleArn
      Environment:
        Variables:
          aaa: bbb
          ccc: ddd
      Layers:
        - !Ref MyLayer
      MemorySize: !FindInMap [EnvMap, !Ref Env, LambdaMemorySize]
      Runtime: python3.8
      Timeout: 5

  Sample2Function:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: app/
      Handler: app.sample2
      Role: !Ref RoleArn
      Environment:
        Variables:
          aaa: bbb
          ccc: ddd
          eee: fff
      Layers:
        - !Ref MyLayer
      MemorySize: !FindInMap [EnvMap, !Ref Env, LambdaMemorySize]
      Runtime: python3.8
      Timeout: 5

# ...

Globalsにまとめる

Serverlessのテンプレートでは, globalsに共通部分をまとめることができます.


Globals:
  Function:
    CodeUri: app/
    Environment:
      Variables:
        aaa: bbb
        ccc: ddd
    MemorySize: !FindInMap [EnvMap, !Ref Env, LambdaMemorySize]
    Layers:
      - !Ref MyLayer
    Runtime: python3.8
    Timeout: 5

Resources:
  SampleFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: app.sample
      Role: !Ref RoleArn

  Sample2Function:
    Type: AWS::Serverless::Function
    Properties:
      Handler: app.sample2
      Role: !Ref RoleArn
      Environment:
        Variables:
          eee: fff

スッキリしました!

Globalsは, Resourcesに書いたものとmergeされ, 同じキーの値はResourcesの値が優先されます.

Globalsにまとめられるもの

ここによると,

  • AWS::Serverless::Function のほとんど(Events, Roleは無理)
  • AWS::Serverless::Api のほとんど
  • AWS::Serverless::HttpApi の一部
    • Auth
    • AccessLogSettings
    • StageVariables
    • Tags
  • AWS::Serverless::SimpleTable
    • SSESpecification

最も数が増えやすいLambdaは殆どをGlobalsにまとめられるので, 積極的に活用していきましょう

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0