How to deploy AWS Lambda Ruby script that requires gem installation with Serverless Framework.
You can easily do it by inserting a plugin.
serverless plugin install -n serverless-ruby-layerGemfile$ 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
Three files will be generated.
.gitignore
handler.rb
serverless.yml
Install a plugin called serverless-ruby-layer.
$ serverless plugin install -n serverless-ruby-layer
The following files and directories will increase.
node_modules
package.json
package-lock.json
Since Serverless Framework is implemented in Node.js, it seems that node_modules and package.json exist even though it is a Ruby project.
serverless.yml
serverless.yml has the following contents. The description of plugins is added without permission when the plugin is installed.
service: sample
frameworkVersion: '2'
provider:
name: aws
runtime: ruby2.7
region: ap-northeast-1
functions:
hello:
handler: handler.hello
plugins:
- serverless-ruby-layer
Gemfile
Create a Gemfile with the following contents.
Let's use holiday_japan as a sample of gem. A gem that determines Japanese holidays.
source "https://rubygems.org"
gem 'holiday_japan'
handler.rb
require 'json'
require 'holiday_japan'
def hello(event:, context:)
holidayName = HolidayJapan.name(Date.new(2021, 8, 8))
puts(holidayName) #To CloudWatch"Mountain day"Is written out
end
If you create it so far and then deploy it with the serverless command, not only the Lambda itself but also the serverless command will automatically create a gem-installed image and upload it as a layer of AWS Lambda.
$ serverless deploy -v
Looking at the deployment results in the AWS Management Console, it looks like this:
Lambda

Layer

Execution result CloudWatch Logs

-(Python version) Pip installation in Serverless Framework and AWS Lambda with Python environment
Recommended Posts