At AWS re:Invent 2018, it was announced that Ruby is now a supported language for AWS Lambda. In this post, I walk you through how to write your very first Ruby-based Lambda function from scratch, followed by how to configure, deploy, and test a Lambda function.
API Gateway will forward incoming requests to the target Ruby based Lambda function, which will call the corresponding DynamoDB operation on the movies table.
To get started, create a Lambda execution role with permission to invoke the Scan operation on the DynamoDB table:
The function entry-point below is is self explanatory, it uses the AWS SDK (the package is pre-installed in Lambda) to instantiate a DynamoDB client in the appropriate region and issues the Scan operation on the DynamoDB table (defined in an environment variable):
The AWS SDK for Ruby is included in the Lambda execution environment by default.
Now that our handler is defined, head to the Lambda form creation and select the IAM role (you might need to refresh the page for the changes to take effect) from the Existing role drop-down list. Then, click the Create function button:
Set the table name as an environment variable:
The movies table contains a set of movies:
Create a deployment package (zip file) and update the function’s code using the AWS CLI command:
Make sure to set the Lambda function handler to handler.lambda_handler
Once the function has been deployed, invoke it manually using the sample event data by clicking on the “Test” button in the top right of the console.
So far, we learned how to build our first Lambda function with Ruby. We also learned how to invoke it manually from the console. To leverage the power of Lambda, we are going to learn how to trigger this Lambda function in response to incoming HTTP requests (event-driven architecture) using the AWS API Gateway service:
Create a deployment stage and open your favorite browser with the API Invoke URL; you should see a message like the one shown in the following screenshot:
The following screenshot shows a properly configured Ruby based Lambda function with IAM access to DynamoDB:
Like what you’re reading? Check out my book and learn how to build, secure, deploy and manage production-ready Serverless applications in Golang with AWS Lambda.