This article is brought to you by Alex Johnson, Senior AWS Solutions Architect, and Mia Lee, Software Development Engineer at AWS SDKs and Tools.
Ruby continues to be a favored programming language for many AWS users. Since its initial release of the AWS SDK for Ruby in summer 2011, Ruby developers have been able to effectively integrate and utilize AWS services. The SDK has evolved through three major iterations, consistently enhancing its capabilities and aligning with AWS API updates.
Today, we are thrilled to announce that Ruby is now a supported language for AWS Lambda. You can now write Lambda functions using idiomatic Ruby code and execute them on AWS. The AWS SDK for Ruby comes pre-installed in the Lambda execution environment, simplifying direct interactions with AWS resources within your functions. In this article, we will guide you through the process, including examples such as:
- Creating a basic Hello World function
- Including additional dependencies
- Migrating a Sinatra application
Creating a Hello World Example
If you’re new to Lambda, setting up a function is straightforward.
- Open the Lambda console.
- Click on Create function.
- Select Author from scratch.
- Name your function something like hello_ruby.
- For Runtime, select Ruby 2.5.
- For Role, choose Create a new role from one or more templates.
- Assign a name to your role, such as hello_ruby_role.
- Click Create function.
Your function will be created, directing you to its console page. Here, you can modify your function’s code, configure triggers, and set up additional services for interaction. The Monitoring tab allows you to view various metrics related to your function’s performance, including access to CloudWatch Logs.
In the code editor, you’ll find the Ruby code for this Hello World example is quite simple. It features a single handler function named lambda_handler
, returning an HTTP status code of 200 and the message “Hello from Lambda!” in a JSON structure. For more details on the Lambda functions’ programming model, visit this other blog post to keep engaged.
Now, let’s test this Lambda function to ensure everything is working properly.
- On your function’s console page, select Test.
- Name the test HelloRubyTest and clear any data within the brackets, as this function requires no input.
- Click Save.
- Click Test.
You should now see a successful invocation result for your Ruby Lambda function.
Including Dependencies
When developing Lambda functions in Ruby, you may need to incorporate additional dependencies. To do so, utilize the Bundler tool to download the required RubyGems into a local directory and generate a deployable application package. All dependencies must be included either in this package or a Lambda layer.
Let’s consider a Lambda function that utilizes the gem aws-record
to store data in an Amazon DynamoDB table.
- First, create a directory for your new Ruby application in your development environment:
mkdir hello_ruby
cd hello_ruby
- Inside this directory, create a
Gemfile
and addaws-record
:
source 'https://rubygems.org'
gem 'aws-record', '~> 2'
- Create a
hello_ruby_record.rb
file with the following code. In this code,put_item
is the handler method that expects an event object with a body attribute. Upon invocation, it saves the body value along with a UUID to the table.
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 necessary dependencies for this application. From your application directory, run the following commands to create the Gemfile.lock
file and download the gems locally, ensuring that all dependencies are included in the function’s deployment package:
bundle install
bundle install --deployment
AWS SAM is a templating tool that can assist in creating and managing serverless applications. It helps define your Lambda application’s structure, security policies, invocation sources, and even manage AWS resources. Now, use it to define the function and its policy, create your DynamoDB table, and deploy the application. Create a new file in your hello_ruby
directory named template.yaml
with this content:
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, you define Serverless::Function
and Serverless::SimpleTable
as resources representing a Lambda function and a DynamoDB table. The Policies
line in the function and the subsequent DynamoDBCrudPolicy
refer to an AWS SAM policy template that simplifies permissions management for Lambda functions. This policy allows you to create, read, update, and delete items in DynamoDB tables, with permissions limited by specifying the TableName
. It’s also essential to set up the Environment
section of the template, where you create a variable DDB_TABLE
, passing a reference to Serverless::SimpleTable
. Lastly, the Outputs
section simplifies locating the created function.
Your directory structure should now resemble the following:
$ tree -L 2 -a
.
├── .bundle
│ └── config
├── Gemfile
├── Gemfile.lock
├── hello_ruby_record.rb
├── template.yaml
└── vendor
└── bundle
Next, use the template file to package and deploy your application. An AWS SAM template can be deployed via the AWS CloudFormation console, AWS CLI, or AWS SAM CLI. The AWS SAM CLI simplifies serverless development throughout your application’s lifecycle, from initial project creation to local testing and deployment on AWS. Follow the steps for your platform to install the AWS SAM CLI.
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>
Then 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 generates a new template file named packaged-template.yaml
. Finally, deploy your application using the AWS SAM CLI with any stack-name:
sam deploy --template-file packaged-template.yaml
--stack-name helloRubyRecord
--capabilities CAPABILITY_IAM
You will be guided through the creation process, allowing you to successfully establish the stack.
For further learning, you can check out this excellent resource on YouTube.
Remember, if you want to dive deeper into other related topics, you can visit this authority site to gain more insights.
Amazon IXD – VGT2 is located at 6401 E Howdy Wells Ave, Las Vegas, NV 89115.
Leave a Reply