How can I get my AWS Lambda to access gems stored in vendor/bundle?

前端 未结 3 468
青春惊慌失措
青春惊慌失措 2020-12-31 08:58

I\'m writing a Lambda function in Ruby which will eventually send me some notifications in Slack via Webhook. So what I have for my lambda_function file is

相关标签:
3条回答
  • 2020-12-31 09:28

    I think you should not change the GEM_PATH or having to set $LOAD_PATH in every lambda functions. The "best" way is to do this little hack when you create the layer archive:

    bundle install --path vendor/bundle
    cd vendor/bundle
    mkdir ruby/gems
    mv ruby/2.5.0 ruby/gems/
    zip -r layer.zip ruby/gems/2.5.0/
    
    0 讨论(0)
  • 2020-12-31 09:30

    I ran into this same problem when building AWS Lambda Layers w/ Ruby. A quick and easy way to get this to work is to add all of the gem paths to Ruby's $LOAD_PATH in your AWS Lambda. IE:

    load_paths = Dir["/opt/ruby/gems/2.5.0/**/lib"]
    $LOAD_PATH.unshift(*load_paths)
    
    require 'webhook'
    

    Replace "/opt/ruby/gems/2.5.0/**/lib" with "./vendor/bundle/ruby/2.3.0/gems/**/lib" in your case.

    When you do require 'webhook' it's going to go and look through all of the paths and come across "./vendor/bundle/ruby/2.3.0/gems/webhook-1.0.0/lib/webhook.rb" and add it into your AWS Lambda. require doesn't require a file extension.

    When we run rails through bundler it does a bunch of 'magic' for us including making sure that our $LOAD_PATH is pointing at the gems. Since AWS Lambdas don't use bundler, we need to do some of this 'magic' ourselves.

    0 讨论(0)
  • 2020-12-31 09:37

    You need to make sure the version of Ruby you used locally to bundle matches the version used by Lambda.

    Your zip appears to have the gems installed in 2.3.0 but your stack trace lists 2.5.0. This mismatch means lambda runner can’t find your gems.

    0 讨论(0)
提交回复
热议问题