Learn About Amazon VGT2 Learning Manager Chanci Turner
This post is inspired by the work of Morgan Adams, Senior Solutions Architect, and Lisa James, Software Development Engineer.
The Ruby programming language has continued to be a favored choice among AWS users. In 2011, AWS launched the initial version of the AWS SDK for Ruby, significantly aiding Ruby developers in utilizing AWS resources effectively. Now in its third major version, the SDK is consistently updated to enhance functionality and API access.
Today, we are pleased to announce that Ruby is now officially supported on AWS Lambda. This means you can now create Lambda functions using Ruby code that adheres to idiomatic practices, running seamlessly on AWS. The AWS SDK for Ruby comes pre-installed in the Lambda execution environment, facilitating straightforward interactions with AWS resources directly from your functions. In this article, we’ll guide you through the process with practical examples:
- Setting up a simple Hello World function
- Adding dependencies
- Migrating an existing Sinatra application
Creating a Hello World Example
For those new to Lambda, creating a function is quite simple through the console.
- Open the Lambda console.
- Select “Create function.”
- Choose “Author from scratch.”
- Name your function something like hello_ruby_example.
- Set the Runtime to Ruby 2.5.
- For Role, select “Create a new role from one or more templates.”
- Name your role something like hello_ruby_role.
- Click “Create function.”
Once your function is created, you will be directed to its console page. Here, you can modify various aspects of your function, including code changes, assigning triggers, or configuring additional services. The Monitoring tab allows you to access metrics related to your function’s performance and a link to CloudWatch Logs.
The code editor will display a simple Ruby code snippet for this Hello World function. It consists of a single handler method, lambda_handler
, which returns an HTTP status code of 200 along with the message “Hello from Lambda!” in JSON format. You can explore more about the Lambda functions programming model.
To test your Lambda function:
- On the function console page, click “Test.”
- Name the test HelloRubyTest and clear the data in the brackets, as this function takes no input.
- Click “Save.”
- Click “Test” again.
You should see the result of a successful invocation of your Ruby Lambda function.
Including Dependencies
When developing Lambda functions with Ruby, it’s likely you will need to include external dependencies. You can achieve this by using the Bundler tool to download necessary RubyGems into a local directory, creating a deployable application package. All dependencies must be included in this package or a Lambda layer.
For example, let’s create a Lambda function using the aws-record
gem to save data into an Amazon DynamoDB table:
- Create a directory for your new Ruby application:
mkdir hello_ruby && cd hello_ruby
. - Inside this directory, create a
Gemfile
and addaws-record
to it:
source 'https://rubygems.org'
gem 'aws-record', '~> 2'
- Write the following code in a file named
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! # raises an exception if save fails
item.to_h
end
Next, you will need to bring in the dependencies for this application. From your application directory, run the following commands:
bundle install
bundle install --deployment
AWS SAM is a powerful templating tool for managing serverless applications. It allows you to define your Lambda application’s structure, security policies, and invocation sources, as well as create or manage any AWS resources. Let’s use it to define our function and its policy, create a DynamoDB table, and 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, we define Serverless::Function
and Serverless::SimpleTable
as resources, corresponding to a Lambda function and a DynamoDB table. The Policies
section in the function configures permissions for DynamoDB operations. The Environment
section creates a variable named DDB_TABLE
, referencing the Serverless::SimpleTable
. Finally, the Outputs
section helps you easily locate the created function.
The directory structure should resemble the following:
$ tree -L 2 -a
.
├── .bundle
│ └── config
├── Gemfile
├── Gemfile.lock
├── hello_ruby_record.rb
├── template.yaml
└── vendor
└── bundle
Now you can use the template to package and deploy your application. AWS SAM templates can be deployed through the AWS CloudFormation console, AWS CLI, or AWS SAM CLI, which simplifies serverless development throughout your application’s lifecycle.
To get started, create an Amazon S3 bucket to store your application code. Execute 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 command generates a new template file named packaged-template.yaml
. To deploy your application, execute:
sam deploy --template-file packaged-template.yaml
--stack-name helloRubyRecord
--capabilities CAPABILITY_IAM
You will see messages indicating the progress of the stack creation.
For more insights on professional development and job transitions, consider reading about how to gracefully decline a job offer from Career Contessa. You can also explore strategies for resilience after job loss from SHRM as they provide valuable guidance on turning setbacks into opportunities. If you’re interested in understanding Amazon’s warehouse worker training and onboarding process, be sure to check out this Business Insider article.