【AWS】CloudformationでLambda Layer実装

1. 使用するサービス

(AWS)

  • Cloudformation
  • Lambda
  • Lambda Layer


2.概要

CloudformationでLambda Layerを実装する手順を説明します。
大まかな手順としては以下になります。

①Layerの中身を作成し、zipにする

②CodeBuildでzip化したLayerを指定したS3に入れる

③Cloudformationで指定したS3からzipファイルを選択してLayerを構築する


3. 実装

3-1. Layerの中身作成

フォルダ構成は以下のようにします。

Layer
    |
    |--LayerContent
                 |
                 |--python
                          |
                          |--layer.py
   

例としてファイル名はlayer.pyとし、zip化する対象はLayerContent直下になります。理由としては、Lambda上でのLayerの展開先はopt/pythonになるからです。
layer.pyの中身は任意の物で大丈夫です。importしたい形にしてください。

3-2. CodeBuildでzip化してS3に保存

CodePipelineで実装するイメージで、github等で作成したLayerをCodeBuidのステージでzip化し、S3に送ります。

version: 0.2
phases:
  install:
    runtime-versions:
        python: 3.8
    commands:
      - pip install --upgrade awscli boto3 mock pymysql==0.10.1
      - cd layer/LayerContent
      - zip -r layer.zip python
      - aws s3 cp ./layer.zip s3のURL
      - rm rdsconnection.zip
      - cp -r python/rdsConnection ../../
      - cd ../..
      
  build:
    commands:
      - python -m unittest discover tests/Unit
      - aws cloudformation package --template-file template.yml --s3-bucket $BUCKET --output-template-file outputtemplate.yml
      - aws s3 sync ./public/ $WEB_BUCKET$Stage --delete

主にinstallの部分がLayer関係です。zipにして指定したS3に送っているだけです。適宜S3のURLを編集してください。

3-3. CloudformationでLayer作成

以下、yamlでLayer及び、Lambdaへのアタッチを行います。

TestLayer:
    Type: "AWS::Lambda::LayerVersion"
    Properties:
      CompatibleRuntimes: 
        - python3.8
      Content: 
        S3Bucket: !Ref LayerBucketName
        S3Key: layer.zip    #Layer File
      Description: "test module layer"
      LayerName: !Sub "${Project}-${Stage}-TestLayer"

  LayerFunction:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: !Sub "${Project}-${Stage}-LayerFunction"
      Handler: index.handler
      Runtime: python3.8
      CodeUri: ./layerfunction
      Role: !GetAtt layerRole.Arn
      Layers:
        - !Sub "arn:aws:lambda:${AWSRegion}:${AccountId}:layer:${Project}-${Stage}-TestLayer:1"
  

LambdaからLayerを指定する場合は、バージョンまで必要なので注意が必要です。
各種パラメータも適宜編集お願いします。
また、Runtimeも合わせる必要があります。

4. おわりに

以上で、Layerの実装が出来ました。注意点としては、Layerをソースレベルで更新しても、Layerのデプロイまではされないので、yamlの更新やバージョンの再指定を忘れずにお願いします。