Khi Ruby support trên AWS Lambda announced hôm qua, tôi excited phải try ngay. Chúng tôi dùng Lambda at Honeybadger, longed write functions in Ruby. Sau vài giờ play với Ruby support mới, confident sẽ spend less time với Node, Go, Python. :)
Quick Example
Announcement blog post AWS get up and running quickly Ruby on Lambda, nhưng tôi muốn share example dùng Serverless framework deploy Ruby Lambda functions. Framework này fantastic job removing annoyances working Lambda. Current version (1.34) không có template generation cho Ruby projects yet (PR merged vài giờ trước tôi viết), nhưng easy start without generator. Sample config file walkthrough, simple function populate DynamoDB table với metadata associated S3 objects khi created:
Resources section config → automatic creation DynamoDB table, name newly-created table placed environment variable cho function, dùng trong code. Function triggered by SNS events cho SNS topic created previously. SNS topic receives notifications PUT events on S3 bucket, also created manually.
Ruby code:
Code không làm nhiều — receive SNS events, loop records SNS messages get info each S3 object created, perform HEAD request S3 object get metadata, put (create/update) item DynamoDB table. Only dependency: AWS SDK, included runtime environment, không cần Gemfile. Tuy nhiên, additional gems muốn bring, easy. Look at include additional gems khi talk deployment.
Deployment
Get code current state to Lambda super easy, thanks Serverless framework:
sls deploy
One command làm all:
- Zip up code
- Put zip file onto S3
- Deploy function Lambda (complete env vars và SNS trigger)
- Create IAM policies
- Create DynamoDB table
Deployment done, tạo objects bucket → new items added DynamoDB table.
Dependencies
Include additional gem dependencies deployed function easy — tạo Gemfile, add gems muốn bundle, run bundle install --path vendor/bundle. Bundle gems vào local directory, zipped up added function với code.
Caveat dependencies: gems require C extension compile. Development env different Lambda runtime, need more work compile extensions work AWS. Thanks lambci Docker images, và Docker image tôi tạo on top their Ruby image, not hard. Bundle dependencies compiled properly, run docker image:
docker run --rm -v $(pwd):/var/task stympy/lambda-ruby2.5
Chỉ run bundler command line trên, gems placed vendor/bundle, ready included ZIP file created by deploy.
Với đó, off to the races. Hy vọng enjoy running Ruby in Lambda như tôi. :)