7
6

More than 5 years have passed since last update.

超シンプルなLambda Layersのサンプル(Python、Serverless Framework使用)

Posted at

Layer

複数のLambdaから呼ばれる共通モジュールをイメージ。

ディレクトリ構成
common
├── serverless.yml
└── layer
    └── python
        └── util.py
serverless.yml
service: sample-layer

provider:
  name: aws

layers:
  samplelayer:
    path: layer
util.py
def hello():
    print('Hello, Lambda Layers World!')

Lambda Function

上記のLayerモジュールを呼び出すLambda。

ディレクトリ構成
function
├── serverless.yml
└── handler.py
serverless.yml
service: sample-function

provider:
  name: aws
  runtime: python3.7
  iamRoleStatements:
  - Effect: "Allow"
    Action:
    - "lambda:InvokeFunction"
    Resource: "*"

functions:
  samplefunction:
    handler: handler.handle_request
    layers:
      - {上記のLayerをsls deployした時に表示されるarn}
handler.py
import util

def handle_request(event, context):
    util.hello()

実行結果

LambdaLayers.png

注意点など

  • Layerは/optに展開される。ここにはパスが通っており、Pythonだと/opt/python/opt/python/lib/python3.7/site-packagesが使えるので、Layerもpythonディレクトリを含めたディレクトリ構成にする必要がある。
  • デプロイされたLayerの中身はコンソール上で見たり編集したりすることができない。
  • Layerはデプロイする度にバージョンが上がり、ARNも変わる。今回の例のように別スタックからARNでLayerを参照する場合は、Layerをデプロイしたら他の参照しているLambdaもデプロイし直す必要がある。
7
6
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
7
6