Has anyone used Crystal with lambda?

Has anyone used Crystal with AWS Lambda? any examples out there that I can take a look at ?

Thank you!

1 Like

Some resources you might find useful (I just got them from searching the web):

1 Like

Thank you! I’ll take a look and update this with my experiences

1 Like

It took me forever to get back to this, but here’s a short working example of Crystal code in a lambda - maybe it will help someone else:

Create a new app:

cd /tmp
crystal init app crystal-lambda01
cd crystal-lambda01
mkdir bin

Add the crambda dependency:

cat << EOF >> ./shard.yml
    path: ./crambda

Clone the crambda locally - we do this so we can apply one of the pull requests by @jgaskins

git clone https://github.com/lambci/crambda.git
cd crambda/
git fetch origin pull/2/head:jgaskins/patch-1
git merge jgaskins/patch-1
cd ..
shards install

Add some test code:

cat << EOF > ./src/crystal-lambda01.cr
require "json"
require "crambda"

Crambda.run_handler do |event, context|
  { "hello from Crystal: #{Crystal::VERSION} - also wombats" }

Run a quick local compile to make sure it works - we don’t actually keep the output, we just want to make sure there’s no errors

shards install && crystal build --no-debug src/crystal-lambda01.cr -o /dev/null

if it works, compile as a static binary using alpine Linux - note that we name the output file bootstrap

docker run --rm \
  -v /tmp/crystal-lambda01:/app \
  -w /app crystallang/crystal:1.10.1-alpine \
  sh -c 'shards install && crystal build --no-debug --static src/crystal-lambda01.cr -o bin/bootstrap && strip bin/bootstrap'

zip it up for the lambda:

cd bin
zip lambda.zip bootstrap

create a lambda function using the AWS CLI:

aws lambda create-function \
  --region=us-west-1 \
  --function-name=crystal_test01 \
  --runtime=provided.al2 \
  --package-type=Zip \
  --architectures=x86_64 \
  --role=arn:aws:iam::1234567890:role/your_lambda_aws_role \
  --zip-file=fileb://lambda.zip \

invoke the lambda and output the result to jq:

aws --region=us-west-1 \
  lambda invoke \
  --cli-binary-format raw-in-base64-out \
  --function-name crystal_test01 /dev/stdout | jq .

sample output:

  "hello from Crystal: 1.10.1 - also wombats"
  "StatusCode": 200,
  "ExecutedVersion": "$LATEST"

if you’re done testing, delete the lambda:

aws lambda delete-function \
  --region=us-west-1 \