Blog

How to run Ruby scripts on AWS Lambda using Ansible

AWS Lambda is definitely one of the most fascinating services I have come across in the last years. As a web developer, the prospect of not having to deal with servers and scaling at all anymore, not even in the abstract sense of Heroku's dynos, is exhilarating.

And I'm not even that averse to doing ops stuff like many other developers. For example, I picked up Ansible about two years ago and have been using it to manage my own (DigitalOcean) servers ever since and even replaced Capistrano with a custom Ansible playbook to deploy my Rails apps.

Lambda really reminds me of how Elon Musk talks about reasoning from first principles rather than by analogy. AWS already offered a "traditional" cloud hosting service with EC2, and a managed one with Elastic Beanstalk, but with Lambda they really sat down and said "OK, let's start from scratch. A developers writes some code and wants to run it. We at AWS have all these regions, servers, databases and whatnot. What would be the easiest way we could let developers run their code without caring about any of it?" And the result is Lambda - upload your code in small chunks (functions) and run it, without thinking about servers or scaling at all.

So Lambda currently supports code written in JavaScript, Python and Java. Naturally, I wanted to try it out with some Ruby code though, and as it turns out, you can upload and run any executables in Lambda. So we just need to package our Ruby script with a Ruby runtime into an executable and off we go. Thankfully the awesome guys from Phusion have already done the grunt work with Traveling Ruby, which "lets you create self-contained Ruby app packages for Windows, Linux and OS X."

Googling further, of course someone had already written and released a script you can use to package up your Ruby script with Traveling Ruby and push it to Lambda. I tried it and it worked fine, but since Ansible is my weapon of choice to script and automate every possible workflow, I ported over the Bash script into a Ansible role:

Thanks to Loren Norman who did the bulk of the work by writing the original script!

Instead of using Traveling Ruby one can also go with mruby which Nick Quaranto implemented here. And of course, since Lambda supports Java, it's totally possible to run JRuby as well as shown here!

I am eagerly awaiting the day that AWS announces native Ruby support for Lambda and who knows, maybe at some point we can deploy a full Rails app to Lambda (or one of the competitors, which I'm sure will pop up soon).

Discuss this post on Hacker News

Ideas? Constructive criticism? Think I'm stupid? Let me know in the comments!