Ruby Lambdas with Serverless
This content is more than 4 years old and the cloud moves fast so some information may be slightly out of date.
Ruby Lambdas with Serverless
Support for Ruby was added on AWS Lambda end of November 2018, with support via the Serverless Framework landing on the same day.
The Serverless Framework is the de-facto standard for writing Lambdas currently and is widely used with NodeJS or Python. Their ecosystem is vast, spanning dozens of plugins to automate all the tasks you could imagine. As a Ruby developer, you can use most of these plugins as well.
Installation and First Steps
The framework is written in NodeJS though, so setting it up feels a bit weird. After this, you could use the serverless create -t aws-ruby -p DIRECTORY
command to get an easy start. I will use a slightly different structure in this post though. Let’s create everything with a few commands:
npm install -g serverless
mkdir --parents my_ruby_lambda/src && cd my_ruby_lambda
Serverless uses a YAML file named serverless.yml
for configuring our project
service: my-ruby-lambda
provider:
name: aws
runtime: ruby2.5
region: eu-west-1
functions:
my_ruby_lambda:
memorySize: 256
timeout: 60
handler: src/my_ruby_lambda.main
package:
exclude:
- package*.json
- node_modules/**
Most of these entries are pretty clear, except for the handler
part if you never worked with Lambda. In principle the first part is referencing the file which contains the code, but instead of an extension we mention which function is to be executed. In our example, that is main
.
Now let’s add a small function without much contents in src/my_ruby_lambda.rb
:
def main(event: nil, context: nil)
puts "Hello Lambda"
end
You can go and make Serverless deploy your function:
> sls deploy
Serverless: Packaging service...
Serverless: Excluding development dependencies...
Serverless: Creating Stack...
Serverless: Checking Stack create progress...
.....
Serverless: Stack create finished...
Serverless: Uploading CloudFormation file to S3...
Serverless: Uploading artifacts...
Serverless: Uploading service my-ruby-lambda.zip file to S3 (392 B)...
Serverless: Validating template...
Serverless: Updating Stack...
Serverless: Checking Stack update progress...
.................
Serverless: Stack update finished...
Service Information
service: my-ruby-lambda
stage: dev
region: eu-west-1
stack: my-ruby-lambda-dev
resources: 5
api keys:
None
endpoints:
None
functions:
my_ruby_lambda: my-ruby-lambda-dev-my_ruby_lambda
layers:
None
And now we can execute it with sls invoke --function my_ruby_lambda
. You can see its output in your AWS CloudWatch, if you want to.