😊
AWS LambdaにRustのコードをデプロイする
目的
AWS LambdaにRustのコードをデプロイしたいです。
色々方法がありますが、手動でコンパイルして配置する方法でいきます。
またアーキテクチャはARM64にします。
ディレクトリ構成
- apps
- services
- api
Cargo.toml
- src
main.rs
- infra
- cdk
- lib
cdk-lambda-stack.ts
- build
- api
bootstrap
Rust
ツールの準備
sudo apt install gcc-aarch64-linux-gnu
rustup target add aarch64-unknown-linux-musl musl-tools
コード
Cargo.toml
[package]
name = "api"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
axum-aws-lambda = "0.10.0"
lambda_http = "0.14.0"
tokio = { version="1.43.0", features=["macros", "rt-multi-thread"] }
main.rs
use axum::{
routing::get, Router
};
#[tokio::main]
async fn main() {
// ルーターの作成
let app = Router::new()
.route("/", get(hello_world));
// サーバーの起動
let app = lambda_http::tower::ServiceBuilder::new()
.layer(axum_aws_lambda::LambdaLayer::default())
.service(app);
lambda_http::run(app).await.unwrap();
}
// ハンドラー関数
async fn hello_world() -> &'static str {
"Hello, World!"
}
ビルド
export CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_LINKER=aarch64-linux-gnu-gcc
export CC=aarch64-linux-gnu-gcc
cargo build -p api --release --target aarch64-unknown-linux-musl
mkdir -p infra/build/api
cp ./target/aarch64-unknown-linux-musl/release/api ../../infra/build/api/bootstrap
CDK
lib/cdk-lambda-stack.ts
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as lambda from "aws-cdk-lib/aws-lambda";
import * as path from 'path';
import * as logs from 'aws-cdk-lib/aws-logs';
export class CdkLambdaStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props)
// Lambde
const func = new lambda.Function(this, "LambdaFunction", {
architecture: lambda.Architecture.ARM_64,
functionName: 'hello-world',
handler: "bootstrap",
logRetention: logs.RetentionDays.ONE_DAY,
runtime: lambda.Runtime.PROVIDED_AL2023,
code: lambda.Code.fromAsset(path.join(__dirname, '../../build/api')),
timeout: cdk.Duration.seconds(900),
memorySize: 128,
});
func.addFunctionUrl({
authType: lambda.FunctionUrlAuthType.NONE
});
}
}
まとめ
手動で作るやり方を紹介しました。一般にはcargo lambdaを使った方法が多いのですが、のちのちCIやCDとかで高速化する時に手動の方が便利かなと思っています。
Discussion