Skip to content

aws-samples/rails-lambda-handler

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

56 Commits
 
 
 
 
 
 
 
 
 
 
 
 

AWS Lambda handler sample for Ruby on Rails

This repository includes the following samples.

  • AWS Lambda handler function that launches Ruby on Rails (or other Rack compliant) application
  • Sample application of Ruby on Rails (simple Web API)

How to execute your Ruby on Rails application as AWS Lambda function

1. Copy function handler code to your project

Simply copy a file corresponding to your API Gateway type to the root directory of your Ruby on Rails project.

2. Create AWS Lambda function

You have two options to create Lambda function.

In this sample, we provide sample Dockerfile to build container image of Ruby on Rails.

3. Setup Lambda function

Specify handler name as follows:

  • REST API: lambda_rest.handler
  • HTTP API: lambda_http.handler

Specify environment variables as follows:

Key Example
BOOTSNAP_CACHE_DIR /tmp/cache
RAILS_LOG_TO_STDOUT 1
RAILS_ENV production
RAILS_MASTER_KEY Value of your master.key
RAILS_RELATIVE_URL_ROOT (Optional) Path prefix of your Rails application
... Other variables if needed

About sample application

Sample application provides simple Web APIs to query fixed database contains 'Hello World' message.

GET /messages

[
    {
        "id": 1,
        "text": "Hello, World!",
        "created_at" :"2022-12-15T01:31:59.291Z",
        "updated_at": "2022-12-15T01:31:59.291Z",
        "url": "URL OF THIS MESSAGE"
    }
]

GET /messages/{id}

{
    "id": 1,
    "text": "Hello, World!",
    "created_at" :"2022-12-15T01:31:59.291Z",
    "updated_at": "2022-12-15T01:31:59.291Z",
    "url": "URL OF THIS MESSAGE"
}

How to deploy sample application

cd cdk
npm ci
npx cdk deploy -c railsMasterKey=d1c2ae419e40d2c43006aacdf98cf7f0

After waiting for completion, you will see the outputs like below:

RailsLambdaStack.HttpHttpApiUrlE6BB121E = https://xxxx.execute-api.ap-northeast-1.amazonaws.com/
RailsLambdaStack.RestRestApiUrl2AB183B3 = https://yyyy.execute-api.ap-northeast-1.amazonaws.com/default/

You can test these APIs by using HTTP client such as cURL.

curl https://xxxx.execute-api.ap-northeast-1.amazonaws.com/messages

[
    {
        "id": 1,
        "text": "Hello, World!",
        "created_at" :"2022-12-15T01:31:59.291Z",
        "updated_at": "2022-12-15T01:31:59.291Z",
        "url": "https://xxxx.execute-api.ap-northeast-1.amazonaws.com/messages/1"
    }
]
curl https://yyyy.execute-api.ap-northeast-1.amazonaws.com/default/messages

[
    {
        "id": 1,
        "text": "Hello, World!",
        "created_at": "2022-12-15T01:31:59.291Z",
        "updated_at": "2022-12-15T01:31:59.291Z",
        "url": "https://yyyy.execute-api.ap-northeast-1.amazonaws.com/default/messages/1"
    }
]