AWS Lambda: Install gems in Ruby function

Install gems into lambda function

Rohit Lingayat
2 min readNov 18, 2021

Problem statment:

When we are working on Ruby lambda function and if your lambda is depends on some external libraries(gems) which is not a default part of lambda, then it will give you error cannot load such file -- <gem name>

In my lambda function I want to implement newrelic_rpm gem to redirect all the logs into newrelic. When I include this gem in Gemfile and execute bundle install it get installed but it is not found in the lambda function. Its failing with errors complaining about not being able to find the gem e.g

This is because we’ve told bundler to install the gems, but we haven’t told the lambda ruby runtime where to find the gems when it is actually executing the code. To do we need to load the gem path inside your lambda function and then require newrelic_rpm.

If your AWS lambda relies on gems and to resolve issue which is mentioned above then you will need to do some changes in the code base. create config for bundler in root directory.bundle/config

---
BUNDLE_PATH: "vendor/bundle"
BUNDLE_WITHOUT: "development:test"

It will install all gems in one location i.e vendor/bundlein the root directory. It will package all the gems in one directory and we can easily upload it to Lambda function. Now to override the gem path with your Ruby version, add the below mentioned code at the top of your file containing the handler function.

load_paths = Dir[
"./xyz/vendor/bundle/ruby/2.7.0/gems/**/lib"
]
$LOAD_PATH.unshift(*load_paths)
require 'newrelic_rpm'

now it will start loading your gems in lambda function, and it will work correctly.

cheers! 🍻 now your lambda will invoke without any errors.

Note: When you deploy the lambda function with .zip file archives, make sure that gems which you installed in vendor/bundle folder it should be the part of .zip archives and then upload to AWS lambda.

--

--

Rohit Lingayat

Ruby on Rails | React | AWS | Solr | JQuery | Nodejs | Typescript