Perl日記

日々の知ったことのメモなどです。Perlは最近やってないです。

AWS Lambda を Rust で動かす(Windows でビルド)

実装する

> rustc --version
rustc 1.62.0 (a8314ef7d 2022-06-27)
> cargo new hello_rust_lambda
> cd hello_rust_lambda

lambda_runtimetokio が必要となる。あとは JSON を返したいので、serde_json を使う。

> cargo add lambda_runtime
> cargo add tokio --features macros
> cargo add serde_json

autobins を false にして、生成バイナリ名を bootstrap にする。

Cargo.toml

[package]
name = "hello_rust_lambda"
version = "0.1.0"
edition = "2021"
autobins = false

[dependencies]
lambda_runtime = "0.6.0"
serde_json = "1.0.82"
tokio = { version = "1.20.1", features = ["macros"] }

[[bin]]
name = "bootstrap"
path = "src/main.rs"

JSON「 {"message": "hello, world!"} 」を返すだけのコード。

src\main.rs

use lambda_runtime::{run, service_fn, Error, LambdaEvent};
use serde_json::{json, Value};

#[tokio::main]
async fn main() -> Result<(), Error> {
    let f = service_fn(my_handler);
    run(f).await?;
    Ok(())
}

async fn my_handler(_event: LambdaEvent<Value>) -> Result<Value, Error> {
    Ok(json!({ "message": "hello, world!" }))
}

Windows でビルドする

ビルドするための環境をダウンロードする。

> rustup target add x86_64-unknown-linux-musl
info: downloading component 'rust-std' for 'x86_64-unknown-linux-musl'
info: installing component 'rust-std' for 'x86_64-unknown-linux-musl'
> rustup target list
...
x86_64-pc-windows-msvc (installed)
...
x86_64-unknown-linux-musl (installed)
...

ビルドするための設定ファイルを作る。

.cargo\config.toml

[target.x86_64-unknown-linux-musl]
linker = "rust-lld"

ビルドする。

> cargo build --release --target x86_64-unknown-linux-musl

エクスプローラで開いて、hello_rust_lambda\target\x86_64-unknown-linux-musl\release に移動する。
「bootstrap」のファイル単品を選択して、右クリックして、「送る」から「圧縮(zip 形式)フォルダー」を選んで、「bootstrap.zip」を作成する。

Lambda 関数を作って、zip ファイルをアップロードして、テスト

「アップロード元」から「.zip ファイル」を選んで、上で作った「bootstrap.zip」を選んでアップロードする。

「Test」から「Configure test event」を選んで、空っぽの JSON を入力にする。

実行して Response が {"message": "hello, world!"} になっていれば OK 。

以上。


Github
GitHub - rightgo09/hello_rust_lambda

参考