sdas199421
sdas199421

Reputation: 61

How to require local project library into ruby aws lambda function?

I have a ruby lambda function and now it needs database connection using mysql2.

Now, using lambda function console editor I uploaded my zip file with my library inside vendor/bundle.

I installed the library in my local using below command

bundle install --path vendor/bundle

to install mysql2 ~> 0.5.2 from the Gemfile.

Now, I wrote below code to get data from db

require 'json'
load_paths = Dir.pwd + "/vendor/bundle/ruby/2.5.0/gems/**/lib"
$LOAD_PATH.unshift(*load_paths)
require 'mysql2'
def lambda_handler()
  @db_host  = "host"
  @db_user  = "user"
  @db_pass  = "pass"
  @db_name = "db"

  client = Mysql2::Client.new(:host => @db_host, :username => @db_user, :password => @db_pass, :database => @db_name)
  @cdr_result = client.query("SELECT count(*) from names")
  puts @cdr_result
  { statusCode: 200, body: JSON.generate('Hello from Lambda!') }
end
lambda_handler

but throwing this error in aws lambda

Response:
{
  "errorMessage": "cannot load such file -- mysql2",
  "errorType": "Init<LoadError>",
  "stackTrace": [
    "/var/lang/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require'",
    "/var/lang/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require'",
    "/var/task/replaceFile.rb:4:in `<top (required)>'",
    "/var/lang/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require'",
    "/var/lang/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require'"
  ]
}

Is there any way that I can require the local directory mysql2 gem into my script file having my gems inside vendor/bundle and use these libraries in my ruby script, which is in aws lambda deployment package.

Upvotes: 2

Views: 904

Answers (1)

G SB
G SB

Reputation: 47

Apparently other answers do not work for Ruby 2.7.0.

It worked for me with

$LOAD_PATH.unshift *Dir['/var/task/app_name/vendor/ruby/2.7.0/gems/**/lib']

Be sure to change app_name to the name of your lambda function.

Upvotes: 2

Related Questions