LoginSignup
2
0

More than 3 years have passed since last update.

Serverless + Lambda Layer でのライブラリの共通化

Posted at

概要

Serverless フレームワークを使用して Lambda Layer を作成し、別の Lambda から Layer にあるライブラリを利用する例です。

serverless.yml の設定

Lambda 関数が実行されるサーバーのデフォルトのライブラリ探索パスGEM_PATH$LAMBDA_TASK_ROOT/vendor/bundle/ruby/2.5.0:/opt/ruby/gems/2.5.0です。
一方でbundle install --deploymentしたときにインストールされるパスはvendor/bundle/ruby/2.5.0になります。
よって、Layer としてデプロイするフォルダをleyers以下のpathvendor/bundleとし、GEM_PATH/opt/ruby/2.5.0を加えて上書きしています。

参考:AWS公式 ライブラリの依存関係をレイヤーに含める

また、Serverless での Lambda Layer の詳しい設定はこちらにのっています。

serverless.yml
service: lambda-layers

provider:
  name: aws
  region: ap-northeast-1
  stage: ${opt:stage, 'dev'}
  runtime: ruby2.5
  environment:
    GEM_PATH: $LAMBDA_TASK_ROOT/vendor/bundle/ruby/2.5.0:/opt/ruby/gems/2.5.0:/opt/ruby/2.5.0

package:
  individually: true

functions:
  helloFunc:
    handler: hello.handler
    events:
      - http:
          path: hello
          method: get
    package:
      include:
        - hello.rb
    layers:
      - { Ref: TestLambdaLayer }

layers:
  test:
    path: vendor/bundle
    name: test-${self:provider.stage}
    compatibleRuntimes:
      - ruby2.5

レイヤーとして使うライブラリのインストール

今回は例としてHashidsというライブラリを使用しました。

Gemfile
source "https://rubygems.org"

git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }

# gem "rails"
gem 'hashids'

デプロイに必要のためプロジェクトフォルダへインストールします。

bundle
bundle install --deployment

レイヤーを使用する Lambda 関数の作成

hello.rb
require 'hashids'

def handler(event:, context:)
  hashids = Hashids.new('this is my salt')
  hash = hashids.encode(12_345)

  { statusCode: 200, body: hash }
end

デプロイ & テスト

sls deploy

デプロイが完了すれば、sls invokeでテストができます。以下のような結果が返れば成功です。

sls invoke -f helloFunc
{
    "statusCode": 200,
    "body": "NkK9"
}
2
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
2
0