Giter VIP home page Giter VIP logo

serverless-sinatra-sample's Introduction

Running Ruby Sinatra on AWS Lambda

This sample code helps get you started with a simple Sinatra web app deployed on AWS Lambda. It is tested with Ruby 2.5.x and bundler-1.17.x.

Additional details can be found at: https://aws.amazon.com/blogs/compute/announcing-ruby-support-for-aws-lambda/

Other resources:

Ruby Sinatra on AWS Lambda: https://blog.eq8.eu/article/sinatra-on-aws-lambda.html

We want FaaS for Ruby: https://www.serverless-ruby.org/

What's Here

This sample includes:

  • README.md - this file
  • Gemfile - Gem requirements for the sample application
  • app/config.ru - this file contains configuration for Rack middleware
  • app/server.rb - this file contains the code for the sample service
  • app/views - this directory has the template files
  • spec/ - this directory contains the RSpec unit tests for the sample application
  • template.yaml - this file contains the description of AWS resources used by AWS CloudFormation to deploy your serverless application
  • pipeline-cfn.yaml - this is the CloudFormation template to create the CodePipeline and the other needed resources. You need to fork the repo if you use a personal GitHub token
  • buildspec.yml - this file contains build commands used by AWS CodeBuild

Getting Started

These directions assume you already have Ruby 2.5.x and AWS CLI installed and configured. Please fork the repo and create an access token if you want to create a CodePipeline to deploy the app. The pipeline-cfn.yaml template can be used to automate the process.

To work on the sample code, you'll need to clone your project's repository to your local computer. If you haven't, do that first. You can find a guide here.

  1. Ensure you are using ruby version 2.5.x

  2. Install bundle

     $ gem install bundler -v "~> 1.17"
    
  3. Install Ruby dependencies for this service

     $ bundle install
    
  4. Download the Gems to the local vendor directory

     $ bundle install --deployment
    
  5. Create the deployment package (note: if you don't have a S3 bucket, you need to create one):

     $ aws cloudformation package \
         --template-file template.yaml \
         --output-template-file serverless-output.yaml \
         --s3-bucket { your-bucket-name }
    

    Alternatively, if you have SAM CLI installed, you can run the following command which will do the same

     $ sam package \
         --template-file template.yaml \
         --output-template-file serverless-output.yaml \
         --s3-bucket { your-bucket-name }
    
  6. Deploying your application

     $ aws cloudformation deploy --template-file serverless-output.yaml \
         --stack-name { your-stack-name } \
         --capabilities CAPABILITY_IAM
    

    Or use SAM CLI

     $ sam deploy \
         --template-file serverless-output.yaml \
         --stack-name { your-stack-name } \
         --capabilities CAPABILITY_IAM
    
  7. Once the deployment is complete, you can find the application endpoint from the CloudFormation outputs tab. Alternatively, you can find it under the Stages link from the API gateway console.

Note: You can also use an Application Load Balancer instead of API gateway. For details, please visit https://docs.aws.amazon.com/elasticloadbalancing/latest/application/lambda-functions.html

What Do I Do Next?

If you have checked out a local copy of your repository you can start making changes to the sample code.

Learn more about Serverless Application Model (SAM) and how it works here: https://github.com/awslabs/serverless-application-model/blob/master/HOWTO.md

AWS Lambda Developer Guide: http://docs.aws.amazon.com/lambda/latest/dg/deploying-lambda-apps.html

How Do I Add Template Resources to My Project?

To add AWS resources to your project, you'll need to edit the template.yaml file in your project's repository. You may also need to modify permissions for your project's IAM roles. After you push the template change, AWS CloudFormation provisions the resources for you.

License

This library is licensed under the Apache 2.0 License.

serverless-sinatra-sample's People

Contributors

aarontc avatar bethesque avatar dependabot[bot] avatar equivalent avatar jbesw avatar jpeddicord avatar lefthand avatar makevoid avatar olleolleolle avatar pdlug avatar reznov9185 avatar teknogeek0 avatar xiangshen-dk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

serverless-sinatra-sample's Issues

How do I run this application in my local environment?

I was looking for steps to set this application in my local environment at localhost:3000. So that I can first enhance and test changes in my local environment before deploying it to AWS.

Any steps explaining the above would be greatly helpful

Init error when loading handler lambda.handler -- cannot load such file -- rack

I followed the deployment instructions (here and https://aws.amazon.com/blogs/compute/announcing-ruby-support-for-aws-lambda/, the Sinatra section -- they seem to match).

But when I try to access any of the endpoints of this sample app, I get Internal Server Error. The lambda cloudwatch logs are:

START RequestId: 1f7fc4ff-12d2-11e9-8098-a1246657e2c7 Version: $LATEST
Init error when loading handler lambda.handler
{
"errorMessage": "cannot load such file -- rack",
"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/lambda.rb:17: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'"
]
}
END RequestId: 1f7fc4ff-12d2-11e9-8098-a1246657e2c7
REPORT RequestId: 1f7fc4ff-12d2-11e9-8098-a1246657e2c7	Duration: 384.13 ms	Billed Duration: 400 ms Memory Size: 512 MB	Max Memory Used: 18 MB	
Unknown application error occurred
Init<LoadError>

I suspect I missed something obvious, but I can't find it.

I made no modifications to the code in this project. I cloned it and then:

bundle install
bundle install --deployment
brew tap aws/tap
brew install aws-sam-cli
aws s3 mb s3://hh-pr-status
sam package --template-file template.yaml \
   --output-template-file packaged-template.yaml \
   --s3-bucket hh-pr-status
sam deploy --template-file packaged-template.yaml \
   --stack-name LambdaSinatra \
   --capabilities CAPABILITY_IAM

cloud formation stack types and sort of related question

Hello!

Thank you for putting this together.

I'm at the step of deploying the app, and I have never used cloud formation before, so I'm not sure what is expected. Would be nice if in the readme you mentioned what type of stack we should create -- should it be from a template?

Also, I know this is sort of unrelated, but I'm having trouble using Ruby Lambdas when trying to upload a 3rd party GEM. As in, I'm trying to skip S3, and try just getting the gem recognized in the env. For a really really simple example,

require 'json'
require 'sinatra'

def lambda_handler(event:, context:)
    hsh = { foo: "bar" }
    { statusCode: 200, body: JSON.generate(hsh) }
end

I've tried the combo of:

  1. bundle install
  2. bundle install --deployment
  3. zip the directory
  4. upload the directory

and the env can never find the sinatra gem. Is it necessary to go through the S3 steps? Or do you think i'm missing something?

Thank you for any thoughts!

Feature request: Publish lambda.rb under copyright-free license

It is hard to imagine lambda.rb rewritten in a such manner it would be substantially different from the one published in this repo. The reason is that lambda.rb is sort of API-to-API interface which includes a lot API calls so it will always look as "derivative". As such, it would be nice to have just this one file from this repo under Public Domain or Unlicense.

Possible typo regarding event headers

On this line, there appears to be a typo. It checks if a key named header is available in the event, then uses a key named headers. Is that intentional?

It also modifies the header values to include an HTTP_ prefix. Should it not be the key that is modified?

name and feedback are not properly stored; rspec tests fail

I deployed the solution using directions in README.md. The Feedback portion of the app does not save "name" or "feedback" fields in Dynamo DB properly. Maybe this is due to an AWS API change somewhere along the way?

I have also tried deploying the solution using the pipeline-cfn.yaml CloudFormation template. CodePipeline deployments of the solution fail because rspec test fail on this same issue:

# rspec
..F.

Failures:

  1) HelloWorld Service should POST params to API feedback endpoint with success
     Failure/Error: item.save! # raise an exception if save fails
     
       #<Aws::DynamoDB::Client> received :put_item with unexpected arguments
         expected: ({:condition_expression=>be a kind of String, :expression_attribute_names=>be a kind of Hash, :item=>{...g, "name"=>"Tomas", "ts"=>be within 3 of 1554471349}, :table_name=>"FeedbackServerlessSinatraTable"})
              got: ({:condition_expression=>"attribute_not_exists(#H)", :expression_attribute_names=>{"#H"=>"id"}, :item=...412f-5057-4b7b-bf10-ae7a143b9689", "ts"=>1554471349}, :table_name=>"FeedbackServerlessSinatraTable"})
       Diff:
       @@ -1,9 +1,5 @@
       -[{:condition_expression=>be a kind of String,
       -  :expression_attribute_names=>be a kind of Hash,
       -  :item=>
       -   {"feedback"=>"AWS Lambda + Ruby == <3",
       -    "id"=>be a kind of String,
       -    "name"=>"Tomas",
       -    "ts"=>be within 3 of 1554471349},
       +[{:condition_expression=>"attribute_not_exists(#H)",
       +  :expression_attribute_names=>{"#H"=>"id"},
       +  :item=>{"id"=>"db13412f-5057-4b7b-bf10-ae7a143b9689", "ts"=>1554471349},
          :table_name=>"FeedbackServerlessSinatraTable"}]
       
     # /usr/local/bundle/gems/aws-record-2.3.0/lib/aws-record/record/item_operations.rb:226:in `_perform_save'
     # /usr/local/bundle/gems/aws-record-2.3.0/lib/aws-record/record/item_operations.rb:80:in `save'
     # /usr/local/bundle/gems/aws-record-2.3.0/lib/aws-record/record/dirty_tracking.rb:275:in `save'
     # /usr/local/bundle/gems/aws-record-2.3.0/lib/aws-record/record/item_operations.rb:48:in `save!'
     # ./app/server.rb:64:in `block in <top (required)>'
     # /usr/local/bundle/gems/sinatra-2.0.4/lib/sinatra/base.rb:1635:in `call'
     # /usr/local/bundle/gems/sinatra-2.0.4/lib/sinatra/base.rb:1635:in `block in compile!'
     # /usr/local/bundle/gems/sinatra-2.0.4/lib/sinatra/base.rb:992:in `block (3 levels) in route!'
     # /usr/local/bundle/gems/sinatra-2.0.4/lib/sinatra/base.rb:1011:in `route_eval'
     # /usr/local/bundle/gems/sinatra-2.0.4/lib/sinatra/base.rb:992:in `block (2 levels) in route!'
     # /usr/local/bundle/gems/sinatra-2.0.4/lib/sinatra/base.rb:1040:in `block in process_route'
     # /usr/local/bundle/gems/sinatra-2.0.4/lib/sinatra/base.rb:1038:in `catch'
     # /usr/local/bundle/gems/sinatra-2.0.4/lib/sinatra/base.rb:1038:in `process_route'
     # /usr/local/bundle/gems/sinatra-2.0.4/lib/sinatra/base.rb:990:in `block in route!'
     # /usr/local/bundle/gems/sinatra-2.0.4/lib/sinatra/base.rb:989:in `each'
     # /usr/local/bundle/gems/sinatra-2.0.4/lib/sinatra/base.rb:989:in `route!'
     # /usr/local/bundle/gems/sinatra-2.0.4/lib/sinatra/base.rb:1097:in `block in dispatch!'
     # /usr/local/bundle/gems/sinatra-2.0.4/lib/sinatra/base.rb:1076:in `block in invoke'
     # /usr/local/bundle/gems/sinatra-2.0.4/lib/sinatra/base.rb:1076:in `catch'
     # /usr/local/bundle/gems/sinatra-2.0.4/lib/sinatra/base.rb:1076:in `invoke'
     # /usr/local/bundle/gems/sinatra-2.0.4/lib/sinatra/base.rb:1094:in `dispatch!'
     # /usr/local/bundle/gems/sinatra-2.0.4/lib/sinatra/base.rb:924:in `block in call!'
     # /usr/local/bundle/gems/sinatra-2.0.4/lib/sinatra/base.rb:1076:in `block in invoke'
     # /usr/local/bundle/gems/sinatra-2.0.4/lib/sinatra/base.rb:1076:in `catch'
     # /usr/local/bundle/gems/sinatra-2.0.4/lib/sinatra/base.rb:1076:in `invoke'
     # /usr/local/bundle/gems/sinatra-2.0.4/lib/sinatra/base.rb:924:in `call!'
     # /usr/local/bundle/gems/sinatra-2.0.4/lib/sinatra/base.rb:913:in `call'
     # /usr/local/bundle/gems/rack-protection-2.0.4/lib/rack/protection/xss_header.rb:18:in `call'
     # /usr/local/bundle/gems/rack-protection-2.0.4/lib/rack/protection/path_traversal.rb:16:in `call'
     # /usr/local/bundle/gems/rack-protection-2.0.4/lib/rack/protection/json_csrf.rb:26:in `call'
     # /usr/local/bundle/gems/rack-protection-2.0.4/lib/rack/protection/base.rb:50:in `call'
     # /usr/local/bundle/gems/rack-protection-2.0.4/lib/rack/protection/base.rb:50:in `call'
     # /usr/local/bundle/gems/rack-protection-2.0.4/lib/rack/protection/frame_options.rb:31:in `call'
     # /usr/local/bundle/gems/rack-2.0.6/lib/rack/null_logger.rb:9:in `call'
     # /usr/local/bundle/gems/rack-2.0.6/lib/rack/head.rb:12:in `call'
     # /usr/local/bundle/gems/rack-2.0.6/lib/rack/method_override.rb:22:in `call'
     # /usr/local/bundle/gems/sinatra-2.0.4/lib/sinatra/base.rb:194:in `call'
     # /usr/local/bundle/gems/sinatra-2.0.4/lib/sinatra/base.rb:1957:in `call'
     # /usr/local/bundle/gems/sinatra-2.0.4/lib/sinatra/base.rb:1502:in `block in call'
     # /usr/local/bundle/gems/sinatra-2.0.4/lib/sinatra/base.rb:1729:in `synchronize'
     # /usr/local/bundle/gems/sinatra-2.0.4/lib/sinatra/base.rb:1502:in `call'
     # /usr/local/bundle/gems/rack-test-1.1.0/lib/rack/mock_session.rb:29:in `request'
     # /usr/local/bundle/gems/rack-test-1.1.0/lib/rack/test.rb:266:in `process_request'
     # /usr/local/bundle/gems/rack-test-1.1.0/lib/rack/test.rb:129:in `custom_request'
     # /usr/local/bundle/gems/rack-test-1.1.0/lib/rack/test.rb:66:in `post'
     # ./spec/spec_helper.rb:30:in `api_gateway_post'
     # ./spec/server_spec.rb:36:in `block (2 levels) in <top (required)>'

Finished in 0.06118 seconds (files took 0.4499 seconds to load)
4 examples, 1 failure

Failed examples:

rspec ./spec/server_spec.rb:22 # HelloWorld Service should POST params to API feedback endpoint with success

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.