This post is courtesy of Xiang Shen Senior – AWS Solutions Architect and Alex Wood Software Development Engineer – AWS SDKs and Tools

Ruby remains a popular programming language for AWS customers. In the summer of 2011, AWS introduced the initial release of AWS SDK for Ruby, which has helped Ruby developers to better integrate and use AWS resources. The SDK is now in its third major version and it continues to improve and deliver AWS API updates.

Today, AWS is excited to announce Ruby as a supported language for AWS Lambda.

Now it’s possible to write Lambda functions as idiomatic Ruby code, and run them on AWS. The AWS SDK for Ruby is included in the Lambda execution environment by default. That makes it easy to interact with the AWS resources directly from your functions. In this post, we walk you through how it works, using examples:

Creating a Hello World example

Including dependencies

Migrating a Sinatra application

Creating a Hello World example

If you are new to Lambda, it’s simple to create a function using the console.

Open the Lambda console. Choose Create function. Select Author from scratch. Name your function something like hello_ruby. For Runtime, choose Ruby 2.5. For Role, choose Create a new role from one or more templates. Name your role something like hello_ruby_role. Choose Create function.

Your function is created and you are directed to your function’s console page.

You can modify all aspects of your function, such editing the function’s code, assigning one or more triggering services, or configuring additional services that your function can interact with. From the Monitoring tab, you can view various metrics about your function’s usage as well as a link to CloudWatch Logs.

As you can see in the code editor, the Ruby code for this Hello World example is basic. It has a single handler function named lambda_handler and returns an HTTP status code of 200 and the text “Hello from Lambda!” in a JSON structure. You can learn more about the programming model for Lambda functions.

Next, test this Lambda function and confirm that it is working.

On your function console page, choose Test. Name the test HelloRubyTest and clear out the data in the brackets. This function takes no input. Choose Save. Choose Test.

You should now see the results of a success invocation of your Ruby Lambda function.

Including dependencies

When developing Lambda functions with Ruby, you probably need to include other dependencies in your code. To achieve this, use the tool bundle to download the needed RubyGems to a local directory and create a deployable application package. All dependencies need to be included in either this package or in a Lambda layer.

Do this with a Lambda function that is using the gem aws-record to save data into an Amazon DynamoDB table.

Create a directory for your new Ruby application in your development environment: mkdir hello_ruby cd hello_ruby Inside of this directory, create a file Gemfile and add aws-record to it: source 'https://rubygems.org' gem 'aws-record', '~> 2' Create a hello_ruby_record.rb file with the following code. In the code, put_item is the handler method, which expects an event object with a body attribute. After it’s invoked, it saves the value of the body attribute along with a UUID to the table. # hello_ruby_record.rb require 'aws-record' class DemoTable include Aws::Record set_table_name ENV[‘DDB_TABLE’] string_attr :id, hash_key: true string_attr :body end def put_item(event:,context:) body = event["body"] item = DemoTable.new(id: SecureRandom.uuid, body: body) item.save! # raise an exception if save fails item.to_h end Next, bring in the dependencies for this application. Bundler is a tool used to manage RubyGems. From your application directory, run the following two commands. They create the Gemfile.lock file and download the gems to the local directory instead of to the local systems Ruby directory. This way, they ensure that all your dependencies are included in the function deployment package. bundle install bundle install --deployment AWS SAM is a templating tool that you can use to create and manage serverless applications. With it, you can define the structure of your Lambda application, define security policies and invocation sources, and manage or create almost any AWS resource. Use it now to help define the function and its policy, create your DynamoDB table and then deploy the application.

Create a new file in your hello_ruby directory named template.yaml with the following contents: AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 Description: 'sample ruby application' Resources: HelloRubyRecordFunction: Type: AWS::Serverless::Function Properties: Handler: hello_ruby_record.put_item Runtime: ruby2.5 Policies: - DynamoDBCrudPolicy: TableName: !Ref RubyExampleDDBTable Environment: Variables: DDB_TABLE: !Ref RubyExampleDDBTable RubyExampleDDBTable: Type: AWS::Serverless::SimpleTable Properties: PrimaryKey: Name: id Type: String Outputs: HelloRubyRecordFunction: Description: Hello Ruby Record Lambda Function ARN Value: Fn::GetAtt: - HelloRubyRecordFunction - Arn In this template file, you define Serverless::Function and Serverless::SimpleTable as resources, which correspond to a Lambda function and DynamoDB table. The line Policies in the function and the following line DynamoDBCrudPolicy refer to an AWS SAM policy template, which greatly simplifies granting permissions to Lambda functions. The DynamoDBCrudPolicy allows you to create, read, update, and delete DynamoDB resources and items in tables. In this example, you limit permissions by specifying TableName and passing a reference to Serverless::SimpleTable that the template creates. Next in importance is the Environment section of this template, where you create a variable named DDB_TABLE and also pass it a reference to Serverless::SimpleTable. Lastly, the Outputs section of the template allows you to easily find the function that was created. The directory structure now should look like the following: $ tree -L 2 -a . ├── .bundle │ └── config ├── Gemfile ├── Gemfile.lock ├── hello_ruby_record.rb ├── template.yaml └── vendor └── bundle Now use the template file to package and deploy your application. An AWS SAM template can be deployed using the AWS CloudFormation console, AWS CLI, or AWS SAM CLI. The AWS SAM CLI is a tool that simplifies serverless development across the lifecycle of your application. That includes the initial creation of a serverless project, to local testing and debugging, to deployment up to AWS. Follow the steps for your platform to get the AWS SAM CLI Installed. Create an Amazon S3 bucket to store your application code. Run the following AWS CLI command to create an S3 bucket with a custom name: aws s3 mb s3://<bucketname> Use the AWS SAM CLI to package your application: sam package --template-file template.yaml \ --output-template-file packaged-template.yaml \ --s3-bucket <bucketname> This creates a new template file named packaged-template.yaml. Use the AWS SAM CLI to deploy your application. Use any stack-name value: sam deploy --template-file packaged-template.yaml \ --stack-name helloRubyRecord \ --capabilities CAPABILITY_IAM Waiting for changeset to be created... Waiting for stack create/update to complete Successfully created/updated stack - helloRubyRecord This can take a few moments to create all of the resources from the template. After you see the output “Successfully created/updated stack,” it has completed. In the Lambda Serverless Applications console, you should see your application listed: To see the application dashboard, choose the name of your application stack. Because this application was deployed with either AWS SAM or AWS CloudFormation, the dashboard allows you to manage the resources as a single group with a number of features. You can view the stack resources, its template, recent deployments, metrics, including any custom dashboards you might make.

Now test the Lambda function and confirm that it is working.

Choose Overview. Under Resources, select the Lambda function created in this application: In the Lambda function console, configure a test as you did earlier. Use the following JSON: {"body": "hello lambda"} Execute the test and you should see a success message: In the Lambda Serverless Applications console for this stack, select the DynamoDB table created: Choose Items

The id and body should match the output from the Lambda function test run.

You just created a Ruby-based Lambda application using AWS SAM!

Migrating a Sinatra application

Sinatra is a popular open source framework for Ruby that launched over a decade ago. It allows you to quickly create powerful web applications with minimal effort. Until today, you still would have needed servers to run those applications. Now, you can just deploy a Sinatra app to Lambda and move to a serverless world!

Thanks to Rack, a Ruby webserver interface, you only need to create a simple Lambda function to bridge the gap between the HTTP requests and the serverless Sinatra application. You don’t need to make additional changes to other Sinatra files at all. Paired with Amazon API Gateway and DynamoDB, your Sinatra application runs completely serverless!

For this post, take an existing Sinatra application and make it function in Lambda.

Clone the serverless-sinatra-sample GitHub repository into your local environment.

Under the app directory, find the Sinatra application files. The files enable you to specify routes to return either JSON or HTML that is generated from ERB templates in the server.rb file. ├── app │ ├── config.ru │ ├── server.rb │ └── views │ ├── feedback.erb │ ├── index.erb │ └── layout.erb In the root of the directory, you also find the template.yaml and lambda.rb files. The template.yaml includes four resources: Serverless::Function

Serverless::API

Serverless::SimpleTable

Lambda::Permission In the lambda.rb file, you find the main handler for this function, which calls Rack to interface with the Sinatra application. This application has several dependencies, so use bundle to install them: bundle install bundle install --deployment Package this Lambda function and the related application components using the AWS SAM CLI: sam package --template-file template.yaml \ --output-template-file packaged-template.yaml \ --s3-bucket <bucketname> Next, deploy the application: sam deploy --template-file packaged-template.yaml \ --stack-name LambdaSinatra \ --capabilities CAPABILITY_IAM Waiting for changeset to be created.. Waiting for stack create/update to complete Successfully created/updated stack - LambdaSinatra In the Lambda Serverless Applications console, select your application: Choose Overview. Under Resources, find the ApiGateway RestApi entry and select the Logical ID. Below it is SinatraAPI: In the API Gateway console, in the left navigation pane, choose Dashboard. Copy the URL from Invoke this API and paste it in another browser tab: Add on to the URL a route from the Sinatra application, as seen in the server.rb.

For example, this is the hello-world GET route:

And this is the /feedback route:

Congratulations, you’ve just successfully deployed a Sinatra-based Ruby application inside of a Lambda function!

Conclusion

As you’ve seen in this post, getting started with Ruby on Lambda is made easy via either the AWS Management Console or the AWS SAM CLI.

You might even be able to easily port existing applications to Lambda without needing to change your code base. The new support for Ruby allows you to benefit from the greatly reduced operational overhead, scalability, availability, and pay–per-use pricing of Lambda.

If you are excited about this feature as well, there is even more information on writing Lambda functions in Ruby in the AWS Lambda Developer Guide.

Happy coding!