

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 在 中使用自訂執行期建置 Lambda 函數 AWS SAM
<a name="building-custom-runtimes"></a>

您可以使用 `sam build`命令來建置 Lambda 函數所需的自訂執行期。您可以為函數指定 ，宣告 Lambda `Runtime: provided` 函數使用自訂執行期。

若要建置自訂執行期，請使用 `BuildMethod: makefile`項目宣告`Metadata`資源屬性。您提供自訂 makefile，您可以在其中宣告`build-function-logical-id`包含執行時間建置命令之表單的建置目標。如有必要，您的 makefile 負責編譯自訂執行期，並將建置成品複製到工作流程中後續步驟所需的適當位置。makefile 的位置是由函數資源的 `CodeUri` 屬性指定，且必須命名為 `Makefile`。

## 範例
<a name="building-custom-runtimes-examples"></a>

### 範例 1：以 Rust 撰寫之函數的自訂執行時間
<a name="building-custom-runtimes-examples-rust"></a>

**注意**  
我們建議您使用 建置 Lambda 函數Cargo Lambda。如需詳細資訊，請參閱 [在 Cargo Lambda中使用 建置 Rust Lambda 函數 AWS SAM](building-rust.md)。

下列 AWS SAM 範本宣告 函數，該函數使用以 Rust 撰寫的 Lambda 函數的自訂執行時間，並指示 `sam build` 執行`build-HelloRustFunction`建置目標的命令。

```
Resources:
  HelloRustFunction:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: HelloRust
      Handler: bootstrap.is.real.handler
      Runtime: provided
      MemorySize: 512
      CodeUri: .
    Metadata:
      BuildMethod: makefile
```

下列 makefile 包含要執行的建置目標和命令。請注意， `CodeUri` 屬性設定為 `.`，因此 makefile 必須位於專案根目錄 （也就是與應用程式 AWS SAM 範本檔案相同的目錄）。檔案名稱必須為 `Makefile`。

```
build-HelloRustFunction:
	cargo build --release --target x86_64-unknown-linux-musl
	cp ./target/x86_64-unknown-linux-musl/release/bootstrap $(ARTIFACTS_DIR)
```

如需設定開發環境以執行先前 中`cargo build`命令的詳細資訊`makefile`，請參閱部落格文章[的 Rust 執行期 AWS Lambda](https://aws.amazon.com/blogs/opensource/rust-runtime-for-aws-lambda/)。

### 範例 2：Makefile builder for Python3.12 （使用綁定建置器的替代方法）
<a name="building-custom-runtimes-examples-python"></a>

您可能想要使用未包含在套件建置器中的程式庫或模組。此範例顯示具有 makefile 建置器的 Python3.12 執行時間 AWS SAM 範本。

```
Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: hello_world/
      Handler: app.lambda_handler
      Runtime: python3.12
    Metadata:
      BuildMethod: makefile
```

下列 makefile 包含要執行的建置目標和命令。請注意， `CodeUri` 屬性設定為 `hello_world`，因此 makefile 必須位於 `hello_world` 子目錄的根目錄，且檔案名稱必須為 `Makefile`。

```
build-HelloWorldFunction:
	cp *.py $(ARTIFACTS_DIR)
	cp requirements.txt $(ARTIFACTS_DIR)
	python -m pip install -r requirements.txt -t $(ARTIFACTS_DIR)
	rm -rf $(ARTIFACTS_DIR)/bin
```