サンプル集  >  other  >  RustをLambdaにデプロイ
RustをLambdaにデプロイ
2025/06/07

RustをLambdaにデプロイしようとしましたが今回はできませんでした。。。

◆環境
OS Windows 10 Home 22H2 64bit
  1. cargo-lambdaインストール
  2. プロジェクト作成
  3. cargo run(失敗)
  4. cargo lambda build / deploy
  5. Lambdaのテスト(失敗)
  6. cargo lambda invoke(失敗)
  7. cargo build --release(失敗)
  8. cargo lambda watch(失敗)

cargo-lambdaインストール

PowerShellでのインストールコマンドを実行してみます。

irm https://cargo-lambda.info/install.ps1 | iex

irm https://cargo-lambda.info/install.ps1 | iex
iex : 発生場所 行:24 文字:32
+   $LatestVersion = $curl.exe --ssl-revoke-best-effort -s "https://w
ww ...
+                                ~~~~~~~~~~~~~~~~~~~~~~
式またはステートメントのトークン 'ssl-revoke-best-effort' を使用でき
ません。
発生場所 行:47 文字:8
+ $BinDir\cargo-lambda lambda system --install-zig
+        ~~~~~~~~~~~~~
式またはステートメントのトークン '\cargo-lambda' を使用できません。
発生場所 行:1 文字:45
+ irm https://cargo-lambda.info/install.ps1 | iex
+                                             ~~~
    + CategoryInfo          : ParserError: (:) [Invoke-Expression], P
arseException
    + FullyQualifiedErrorId : UnexpectedToken,Microsoft.PowerShell.Co
mmands.InvokeExpressionCommand

別のコマンドを試してみます。

winget install CargoLambda.CargoLambda

winget install CargoLambda.CargoLambda
'msstore' ソースでは、使用する前に次の契約を表示する必要があります。
Terms of Transaction:
 https://aka.ms/microsoft-store-terms-of-transac
tion
ソースが正常に機能するには、現在のマシンの 2 文字の地理的リージョンを
バックエンド サービスに送信する必要があります (例: "US")。

すべてのソース契約条件に同意しますか?
[Y] はい  [N] いいえ: Y
見つかりました CargoLambda [CargoLambda.CargoLambda] バージョン 1.8.5
このアプリケーションは所有者からライセンス供与されます。
Microsoft はサードパーティのパッケージに対して責任を負わず、ライセン
スも付与しません。
このパッケージには次の依存関係が必要です:
  - パッケージ
      Microsoft.VCRedist.2015+.x64
      zig.zig
(1/1) 見つかりました Zig [zig.zig] バージョン 0.14.1
このアプリケーションは所有者からライセンス供与されます。
Microsoft はサードパーティのパッケージに対して責任を負わず、ライセン
スも付与しません。
ダウンロード中 https://ziglang.org/download/0.14.1/zig-x86_64-windows
-0.14.1.zip

  ██████████████████████████████  78.4 MB / 78.4 MB
インストーラーハッシュが正常に検証されました
アーカイブを展開しています...
アーカイブが正常に展開されました
パッケージのインストールを開始しています...
パス環境変数が変更されました; 新しい値を使用するにはシェルを再起動し
てください。
コマンド ライン エイリアスが追加されました: "zig"

インストールが完了しました

ダウンロード中 https://github.com/cargo-lambda/cargo-lambda/releases/
download/v1.8.5/cargo-lambda-v1.8.5.windows-x64.zip

  ██████████████████████████████  13.4 MB / 13.4 MB
インストーラーハッシュが正常に検証されました
アーカイブを展開しています...
アーカイブが正常に展開されました
パッケージのインストールを開始しています...
パス環境変数が変更されました; 新しい値を使用するにはシェルを再起動し
てください。
コマンド ライン エイリアスが追加されました: "cargo-lambda"

インストールが完了しました

インストールに5~10分程度かかった印象です。

プロジェクト作成

プロジェクトを作成します。

>cd rust-workspace
>cargo lambda new ymwrust008 --http-feature=apigw_rest

VSCodeで開くためにcodeコマンドを実行します。

>code ymwrust008

複数のファイルが生成されていました。


main.rs
 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
use lambda_http::{run, service_fn, tracing, Error};
mod http_handler;
use http_handler::function_handler;

#[tokio::main]
async fn main() -> Result<(), Error> {
    tracing::init_default_subscriber();

    run(service_fn(function_handler)).await
}

http_handler.rs
 1: 
 2: 
 3: 
 4: 
 5: 
 6: 

 7: 

 8: 
 9: 
10: 
11: 
12: 
13: 

14: 
15: 
16: 

17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
27: 
28: 
29: 
30: 
31: 
32: 
33: 
34: 
35: 

36: 
37: 
38: 
39: 

40: 
41: 
42: 
43: 
44: 
45: 
46: 
47: 
48: 
49: 

50: 

51: 
52: 
53: 

54: 
55: 
56: 
57: 
58: 
59: 

60: 
61: 
62: 
63: 

64: 
65: 
66: 
use lambda_http::{Body, Error, Request, RequestExt, Response};

/// This is the main body for the function.
/// Write your code inside it.
/// There are some code example in the following URLs:
/// - https://github.com/awslabs/aws-lambda-rust-runtime/tree/ma
in/examples

pub(crate) async fn function_handler(event: Request) -> Result<R
esponse<Body>, Error> {
    // Extract some useful information from the request
    let who = event
        .query_string_parameters_ref()
        .and_then(|params| params.first("name"))
        .unwrap_or("world");
    let message = format!("Hello {who}, this is an AWS Lambda HT
TP request"
);

    // Return something that implements IntoResponse.
    // It will be serialized to the right response event automat
ically by the runtime

    let resp = Response::builder()
        .status(200)
        .header("content-type""text/html")
        .body(message.into())
        .map_err(Box::new)?;
    Ok(resp)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;
    use lambda_http::{Request, RequestExt};

    #[tokio::test]
    async fn test_generic_http_handler() {
        let request = Request::default();

        let response = function_handler(request).await.unwrap()
;
        assert_eq!(response.status(), 200);

        let body_bytes = response.body().to_vec();
        let body_string = String::from_utf8(body_bytes).unwrap()
;

        assert_eq!(
            body_string,
            "Hello world, this is an AWS Lambda HTTP request"
        );
    }

    #[tokio::test]
    async fn test_http_handler_with_query_string() {
        let mut query_string_parameters: HashMap<String, String>
 = HashMap::new();
        query_string_parameters.insert("name".into(), "ymwrust00
8"
.into());

        let request = Request::default()
            .with_query_string_parameters(query_string_parameter
s);

        let response = function_handler(request).await.unwrap();
        assert_eq!(response.status(), 200);

        let body_bytes = response.body().to_vec();
        let body_string = String::from_utf8(body_bytes).unwrap()
;

        assert_eq!(
            body_string,
            "Hello ymwrust008, this is an AWS Lambda HTTP reques
t"

        );
    }
}

Cargo.toml
1: 
2: 
3: 
4: 
5: 
6: 
7: 

8: 
9: 
[package]
name = "ymwrust008"
version = "0.1.0"
edition = "2021"

[dependencies]
lambda_http = { version = "0.13.0", default-features = false, fe
atures = ["apigw_rest""tracing"] }

tokio = { version = "1", features = ["macros"] }

cargo run

実行してみます。

>cargo run
   Compiling pin-project-lite v0.2.16
   Compiling stable_deref_trait v1.2.0
   Compiling itoa v1.0.15
   :
   Compiling ymwrust008 v0.1.0 (C:\Users\xxx\rust-workspace\ymwrust00
8)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 15.
48s
     Running `target\debug\ymwrust008.exe`

thread 'main' panicked at C:\Users\xxx\.cargo\registry\src\index.crat
es.io-1949cf8c6b5b557f\lambda_runtime-0.13.0\src\lib.rs:68:65:
Missing AWS_LAMBDA_FUNCTION_NAME env var: NotPresent
note: run with `RUST_BACKTRACE=1` environment variable to display a b
acktrace
error: process didn't exit successfully: `target\debug\ymwrust008.exe
` (exit code: 101)

エラーが出る都度必要な環境変数を追加して実行を繰り返しました。

set AWS_LAMBDA_FUNCTION_NAME=ymwrust008
set AWS_LAMBDA_FUNCTION_MEMORY_SIZE=128
set AWS_LAMBDA_FUNCTION_VERSION=1

AWS_LAMBDA_RUNTIME_APIに何を設定すればよいか分からず詰まりました。

別の方法を試してみます。

cargo lambda build / deploy

cargo lambdaコマンドでビルドとデプロイをしてみます。

cd ymwrust008
cargo lambda build --release

>cargo lambda build --release
▪▪▪▪▪ Target component installed
  Downloaded windows_x86_64_gnu v0.52.6
  Downloaded 1 crate (836.4 KB) in 1.37s
   Compiling proc-macro2 v1.0.95
   :
   Compiling lambda_runtime v0.13.0
   Compiling lambda_http v0.13.0
   Compiling ymwrust008 v0.1.0 (C:\Users\xxx\rust-workspace\ymwrust00
8)
    Finished `release` profile [optimized] target(s) in 43.26s

bootstrapというファイルが生成された模様です。

~/ymwrust008
  + target
    + lambda
      + ymwrust008
        - bootstrap

デプロイしてみます。

cargo lambda deploy

>cargo lambda deploy
✅ function deployed successfully 🎉
🛠️  binary last compiled 10 minutes ago
🔍 arn: arn:aws:lambda:ap-northeast-1:886600662200:function:ymwrust0
08
🎭 version: 1

確認するとLambdaができていました!


トリガーには何も設定されていませんでした。 コードも表示されませんでした。

Lambdaのテスト

AWSマネジメントコンソール上でLambdaのテストを実行したところエラーになりました。

この関数はAPI Gatewayなどからのペイロードを引数として期待している、といった感じです。


API Gatewayを設定してみます。



API Gatewayからテストを実施してみましたが結果は同じでした。

いつの間にかzipファイルができていました。

~/ymwrust008
  + target
    + lambda
      + ymwrust008
        - bootstrap
        - bootstrap.zip

別の方法で実行してみます。

cargo lambda invoke

cargo lambda invokeを試してみます。

>cargo lambda invoke --remote ymwrust008
Error:   x no data payload provided, use one of the data flags: `--da
ta-file`, `--data-ascii`, `--data-example`

  Was this behavior unexpected?
  Start a thread in https://github.com/cargo-lambda/cargo-lambda/disc
ussions

data payloadが提供されていないというエラーが出ました。--datafile、--data-ascii、--data-exampleの1つを指定すると良いようです。

--data-asciiでJSON形式の文字列を指定してみます。

>cargo lambda invoke --remote --data-ascii '{"name": "hoge"}' ymwr
ust008
error: unexpected argument 'ymwrust008' found

Usage: cargo lambda invoke [OPTIONS] [FUNCTION_NAME]

For more information, try '--help'.

エラーが出ました。

別の方法を試してみます。

cargo build --release

curgo build --releaseを試してみます。

>cargo build --release --target x86_64-unknown-linux-musl
   Compiling proc-macro2 v1.0.95
   Compiling unicode-ident v1.0.18
   :
   Compiling futures-task v0.3.31
   Compiling futures-io v0.3.31
error[E0463]: can't find crate for `core`
  |
  = note: the `x86_64-unknown-linux-musl` target may not be installed
  = help: consider downloading the target with `rustup target add x86
_64-unknown-linux-musl`

For more information about this error, try `rustc --explain E0463`.
error: could not compile `stable_deref_trait` (lib) due to 1 previous
 error
warning: build failed, waiting for other jobs to finish...
error: could not compile `itoa` (lib) due to 1 previous error
error: could not compile `futures-io` (lib) due to 1 previous error
error: could not compile `futures-sink` (lib) due to 1 previous error
error: could not compile `pin-project-lite` (lib) due to 1 previous e
rror
error: could not compile `pin-utils` (lib) due to 1 previous error
error: could not compile `futures-core` (lib) due to 1 previous error
error: could not compile `futures-task` (lib) due to 1 previous error
error[E0463]: can't find crate for `std`
  |
  = note: the `x86_64-unknown-linux-musl` target may not be installed
  = help: consider downloading the target with `rustup target add x86
_64-unknown-linux-musl`

error: could not compile `fnv` (lib) due to 1 previous error
error: could not compile `once_cell` (lib) due to 1 previous error
error: could not compile `memchr` (lib) due to 1 previous error

x86_64-unknown-linux-muslのダウンロードを検討してくださいとメッセージが出ています。

>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'
 35.5 MiB /  35.5 MiB (100 %)  18.3 MiB/s in  1s ETA:  0s

もう一度試してみます。

>cargo build --release --target x86_64-unknown-linux-musl
   Compiling proc-macro2 v1.0.95
   Compiling pin-project-lite v0.2.16
   :
   Compiling lambda_http v0.13.0
   Compiling ymwrust008 v0.1.0 (C:\Users\xxx\rust-workspace\ymwrust00
8)
error: linker `cc` not found
  |
  = note: program not found

error: could not compile `ymwrust008` (bin "ymwrust008") due to 1 pre
vious error

ccをインストールしてみます。


以下のファイルをダウンロードしました。

vs_BuildTools.exe

「管理者として実行」を行います。


「続行」を押します。


「C++ によるデスクトップ開発」をチェックします。


右下の「インストール」を押します。


インストールしましたが状況は変わりませんでした。

別の方法を試してみます。

cargo lambda watch

cargo lambda watchを試してみます。

>cargo lambda watch
 INFO starting Runtime server runtime_addr=127.0.0.1:9000
 INFO starting lambda function function="_" manifest=Some("Cargo.toml
") cmd=Exec { prog: "\\\\?\\C:\\Users\\xxx\\.rustup\\toolchains\
\stable-x86_64-pc-windows-msvc\\bin\\cargo.exe", args: ["run", "
--color", "auto", "--manifest-path", "Cargo.toml"] }
   Compiling ymwrust008 v0.1.0 (C:\Users\xxx\rust-workspace\ymwrust00
8)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 5.2
7s
     Running `target\debug\ymwrust008.exe`

別のコマンドプロンプトからコマンドを実行します。

>cargo lambda invoke --remote --data-ascii '{"name": "hoge"}' ymwrust
008
error: unexpected argument 'ymwrust008' found

Usagecargo lambda invoke [OPTIONS] [FUNCTION_NAME]

For more information, try '--help'.

>cargo lambda invoke --data-ascii '{"name": "hoge"}'
Error: Missing function

  x that function doesn't exist as a binary in your project. Availabl
e functions: {"ymwrust008"}

  Was this behavior unexpected?
  Start a thread in https://github.com/cargo-lambda/cargo-lambda/disc
ussions

最初のコマンドプロンプトに以下のメッセージが出ました。

ERROR available_functions={"ymwrust008"} detail="that function doesn'
t exist as a binary in your project"

curl http://localhost:9000/2015-03-31/functions/function/invocations 
-d '{}' -H "Content-Type: application/json"

同じメッセージが表示されました。

ymwrust008のバイナリファイルがあるか確認します。

>cargo run --bin help
error: no bin target named `help`.
Available bin targets:
    ymwrust008

helpがないと表示されました。Availableには「ymwrust008」が表示されています。

ymwrust008を指定してみます。

>cargo run --bin ymwrust008
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 2.5
2s
     Running `target\debug\ymwrust008.exe`

thread 'main' panicked at C:\Users\xxx\.cargo\registry\src\index.crat
es.io-1949cf8c6b5b557f\lambda_runtime-0.13.0\src\lib.rs:68:65:
Missing AWS_LAMBDA_FUNCTION_NAME env var: NotPresent
note: run with `RUST_BACKTRACE=1` environment variable to display a b
acktrace
error: process didn't exit successfully: `target\debug\ymwrust008.exe
` (exit code: 101)

以前と同じ環境変数がないというエラーがでました。

cargo lambda watchをCtrl+Cで停止します。

 INFO terminating lambda scheduler
 INFO terminating lambda function function="_"

>cargo lambda watch -f ymwrust008
error: unexpected argument '-f' found

  tip: to pass '-f' as a value, use '-- -f'

Usage: cargo lambda watch [OPTIONS] [args]...

For more information, try '--help'.

-fオプションは無いようです。

煮詰まってしまったので今回はあきらめます。

■試したコマンド
irm https://cargo-lambda.info/install.ps1 | iex
winget install CargoLambda.CargoLambda
rustup target add x86_64-unknown-linux-musl

cargo run
cargo run --bin help
cargo run --bin ymwrust008

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

cargo lambda new ymwrust008 --http-feature=apigw_rest
cargo lambda build --release
cargo lambda deploy
cargo lambda invoke --remote ymwrust008
cargo lambda invoke --remote --data-ascii '{"name": "hoge"}' ymwrust0
08
cargo lambda invoke --data-ascii '{"name": "hoge"}'
cargo lambda watch

curl http://localhost:9000/2015-03-31/functions/function/invocations 
-d '{}' -H "Content-Type: application/json"


2025/09/13 追記

Lambdaのテストで発生したエラーですが、テンプレート - オプションでAPI Gateway AWS Proxyを選択すると正常にテストすることができました!>>>Lambdaのテストリクエスト

▲ PageTop  ■ Home


Copyright (C) 2025 ymlib.com