8
5

More than 3 years have passed since last update.

Serverless FrameworkとAWS Lambda with Rubyの環境にgemインストール

Last updated at Posted at 2021-01-03

gemインストールが必要なAWS LambdaのRubyスクリプトをServerless Frameworkでデプロイする方法です。

手順概要

プラグインを入れれば簡単にできます。

  1. serverless plugin install -n serverless-ruby-layer
  2. Gemfile 作成
  3. あとは普通にデプロイすると勝手にいろいろやってくれる

手順詳細

Serverless Frameworkのサービス作成

$ serverless create --template aws-ruby
Serverless: Generating boilerplate...
 _______                             __
|   _   .-----.----.--.--.-----.----|  .-----.-----.-----.
|   |___|  -__|   _|  |  |  -__|   _|  |  -__|__ --|__ --|
|____   |_____|__|  \___/|_____|__| |__|_____|_____|_____|
|   |   |             The Serverless Application Framework
|       |                           serverless.com, v2.16.1
 -------'

Serverless: Successfully generated boilerplate for template: "aws-ruby"
Serverless: NOTE: Please update the "service" property in serverless.yml with your service name

ファイルが3つ生成されます。

.gitignore
handler.rb
serverless.yml

プラグインインストール

serverless-ruby-layer というプラグインをインストールします。

$ serverless plugin install -n serverless-ruby-layer

以下のファイルやディレクトリが増えます。

node_modules
package.json
package-lock.json

Serverless FrameworkがNode.jsで実装されているので、Rubyのプロジェクトなのに node_modulespackage.json が存在することになるようです。

ソースコード

serverless.yml

serverless.yml は以下の内容にします。 plugins のところの記述はプラグインをインストールすると勝手に追記されています。

service: sample

frameworkVersion: '2'

provider:
  name: aws
  runtime: ruby2.7
  region: ap-northeast-1

functions:
  hello:
    handler: handler.hello

plugins:
  - serverless-ruby-layer

Gemfile

Gemfile を作成し、以下の内容にします。

gemのサンプルとして holiday_japan を使ってみます。日本の祝日を判定するgemです。

source "https://rubygems.org"

gem 'holiday_japan'

Rubyソースコード

handler.rb

require 'json'
require 'holiday_japan'

def hello(event:, context:)
  holidayName = HolidayJapan.name(Date.new(2021, 8, 8))
  puts(holidayName) # CloudWatch に "山の日" と書き出される
end

デプロイ

ここまで作成してから serverless コマンドでデプロイすると、Lambda本体だけでなく、 serverless コマンドが自動でgemインストールしたイメージを作成し、AWS LambdaのLayerとしてアップロードしてくれます。

$ serverless deploy -v

実行

デプロイ結果をAWSマネジメントコンソールで見ると次のように見えます。

Lambda

image.png

Layer

image.png

実行結果のCloudWatch Logs

image.png

リンク

8
5
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
8
5