How to cross compile rust lambda for Amazon Linux 2 Lambda Runtime

December 17, 2023

How to cross compile rust lambda for Amazon Linux 2 Lambda Runtime using Docker and cargo lambda

How to cross compile rust lambda for Amazon Linux 2 Lambda Runtime

Pre-Reqs:

  • Cargo installed
  • Rust installed
  • Rust lambda written and ready to compile
  • Docker desktop installed

Shell Script

This script is available in this GitHub repository

1RUST_TARGET="x86_64-unknown-linux-musl" # Set this to aarch64 or x86_64 -unknown-linux-gnu for ARM or x86 functions. 2 3al2build() { 4 docker run --rm --user "$(id -u)":"$(id -g)" \ 5 -v "${PWD}":/workspace -w /workspace \ 6 ghcr.io/cargo-lambda/cargo-lambda \ 7 cargo lambda build --release --target ${RUST_TARGET} --output-format zip 8} 9 10al2build

I have called this script compile-rust-lambda.zsh

Usage

Docker desktop must be open for this script to execute successfully, otherwise you will get this error:

1docker: Cannot connect to the Docker daemon

To compile my rust lambdas, I open my terminal in the directory the lambda or rust workspace of lambdas are in and execute:

1source ./compile-rust-lambda.zsh

This will output a zip folder containing your lambda function executable, called bootstrap. The zip folder can be found in your rust lambda's workspace /target/lambda/

Cargo Lambda

View aws Documentation for cargo lambda here

I used cargo lambda successfully on my linux machine (I use Manjaro Arch btw) but when I installed and tried to run cargo lambda on my M2 MacBook, the steps in the documentation did not work for me. I was only able to execute the cargo lambda command in a linux based docker image. To save complexity installing cargo lambda on a linux docker image, you can fortunately use a docker image dedicated to cargo lambda that has everything you need installed.


Contact