2

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.

3
  • Make sure, that the files are there... for example can you run there some code, which show the files? for example: What deos this command print? `ls #{Dir.pwd + "/vendor/bundle/ruby/2.5.0/gems"}` Commented Dec 19, 2018 at 12:36
  • Have you tried installing the libmysql-ruby and libmysqlclient-dev libraries? I think the gem is just not installed under your bundle but may be wrong. Commented Dec 19, 2018 at 13:26
  • @DonPaulie it showed this "mysql2-0.5.2\n" Commented Dec 20, 2018 at 5:53

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.