AWS Lambda: Ruby function failing to load gem

扶醉桌前 提交于 2020-01-03 19:04:16

问题


I have a Ruby Lambda function which depends on an external (ie non-AWS) RubyGem. I have a Gemfile, a Gemfile.lock and a vendor/bundle directory. Everything looks fine from a local perspective.

I've tried using bundle install --path vendor/bundle and bundle install --deployment to install the gems, and am specifically including the vendor directory when zipping up the files: zip -r function.zip myfunction.rb vendor

Despite this, when I test the function in the Lambda console, it's failing with errors complaining about not being able to find the libraries, e.g.

{
  "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/hello_ruby_record.rb:3: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'"
  ]
}

Presumably I'm doing something really obviously wrong in bundling up the gems before uploading the function; but I can't figure out what. Does anyone have any ideas?


回答1:


I faced the same issue. The underlying reason is different ruby versions being used in local and Lambda function. Currently AWS Lambda is using Ruby 2.5 and your gems are located at '/vendor/bundle/ruby/'. Thus your lambda function is unable to locate the gem libraries uploaded by you. To override the gem path with your Ruby version, add the below mentioned code at the top of your file containing the handler function:

  my_gem_path = Dir["./vendor/bundle/ruby/<your-ruby-version>/gems/**/lib"]
  $LOAD_PATH.unshift(*my_gem_path)

Or, just try upgrading and matching your local Ruby version with the exact version used by Lambda function viz 2.5 currently.



来源:https://stackoverflow.com/questions/53673486/aws-lambda-ruby-function-failing-to-load-gem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!