

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

# 使用 建置您的應用程式 AWS SAM
<a name="serverless-building"></a>

將基礎設施新增為程式碼 (IaC) 到 AWS SAM 範本後，您就可以使用 **sam build**命令開始建置應用程式。此命令會從應用程式專案目錄中的檔案 （即您的 AWS SAM 範本檔案、應用程式程式碼，以及任何適用的語言特定檔案和相依性） 建立建置成品。這些建置成品可讓您的無伺服器應用程式準備好進行應用程式的後續開發步驟，例如本機測試和部署至 AWS 雲端。測試和部署都會使用建置成品做為輸入。

您可以使用 **sam build**來建置整個無伺服器應用程式。此外，您可以建立自訂組建，例如具有特定函數、 layer 或自訂執行時間的組建。若要進一步了解如何使用 和為什麼使用 **sam build**，請參閱本節中的主題。如需使用 `sam build`命令的簡介，請參閱 [使用 建置 簡介 AWS SAM](using-sam-cli-build.md)。

**Topics**
+ [使用 建置 簡介 AWS SAM](using-sam-cli-build.md)
+ [使用 的預設建置 AWS SAM](serverless-sam-cli-using-build.md)
+ [使用 自訂組建 AWS SAM](building-lambda-functions.md)

# 使用 建置 簡介 AWS SAM
<a name="using-sam-cli-build"></a>

使用 AWS Serverless Application Model Command Line Interface (AWS SAM CLI) `sam build`命令，為您的無伺服器應用程式準備開發工作流程中的後續步驟，例如本機測試或部署到 AWS 雲端。此命令會建立`.aws-sam`目錄，以 和 `sam deploy`所需的格式`sam local`和位置來建構您的應用程式。
+ 如需 的簡介 AWS SAM CLI，請參閱 [什麼是 AWS SAM CLI？](what-is-sam-overview.md#what-is-sam-cli)。
+ 如需`sam build`命令選項的清單，請參閱 [sam build](sam-cli-command-reference-sam-build.md)。
+ 如需在典型開發工作流程`sam build`期間使用 的範例，請參閱 [步驟 2：建置您的應用程式](serverless-getting-started-hello-world.md#serverless-getting-started-hello-world-build)。

**注意**  
使用 `sam build`需要您從開發機器上無伺服器應用程式的基本元件開始。這包括 AWS SAM 範本、 AWS Lambda 函數程式碼，以及任何語言特定的檔案和相依性。如需詳細資訊，請參閱 [在 中建立您的應用程式 AWS SAM](using-sam-cli-init.md)。

**Topics**
+ [使用 sam build 建置應用程式](#using-sam-cli-build-apps)
+ [本機測試和部署](#using-sam-cli-build-test-deploy)
+ [最佳實務](#using-sam-cli-build-best)
+ [sam 建置的選項](#using-sam-cli-build-options)
+ [疑難排解](#using-sam-cli-build-troubleshooting)
+ [範例](#using-sam-cli-build-examples)
+ [進一步了解](#using-sam-cli-build-learn)

## 使用 sam build 建置應用程式
<a name="using-sam-cli-build-apps"></a>

使用 之前`sam build`，請考慮設定下列項目：

1. **Lambda 函數和 layer** – `sam build`命令可以建置 Lambda 函數和 layer。若要進一步了解 Lambda 層，請參閱 [在 中建置 Lambda 層 AWS SAM](building-layers.md)。

1. **Lambda 執行時間** – *執行時間*提供特定語言的環境，可在叫用時在執行環境中執行函數。您可以設定原生和自訂執行時間。

   1. **原生執行時間** – 在支援的 Lambda 執行時間中編寫 Lambda 函數，並建置函數以在 中使用原生 Lambda 執行時間 AWS 雲端。

   1. **自訂執行時間** – 使用任何程式設計語言撰寫 Lambda 函數，並使用 makefile或第三方建置器中定義的自訂程序建置執行時間，例如 esbuild。如需詳細資訊，請參閱 [在 中使用自訂執行期建置 Lambda 函數 AWS SAM](building-custom-runtimes.md)。

1. **Lambda 套件類型** – Lambda 函數可以封裝在下列 Lambda 部署套件類型中：

   1. **.zip 檔案封存** – 包含您的應用程式程式碼及其相依性。

   1. **容器映像** – 包含基本作業系統、執行時間、Lambda 延伸模組、您的應用程式程式碼及其相依性。

使用 初始化應用程式時，可以設定這些應用程式設定`sam init`。
+ 若要進一步了解如何使用 `sam init`，請參閱 [在 中建立您的應用程式 AWS SAM](using-sam-cli-init.md)。
+ 若要進一步了解如何在應用程式中設定這些設定，請參閱 [使用 的預設建置 AWS SAM](serverless-sam-cli-using-build.md)。

**建置應用程式**

1. `cd` 您專案的根目錄。這與 AWS SAM 範本的位置相同。

   ```
   $ cd sam-app
   ```

1. 執行下列命令：

   ```
   sam-app $ sam build <arguments> <options>
   ```
**注意**  
常用的選項是 `--use-container`。如需詳細資訊，請參閱 [在提供的容器內建置 Lambda 函數](#using-sam-cli-build-options-container)。

   以下是輸出的範例 AWS SAM CLI：

   ```
   sam-app $ sam build
   Starting Build use cache
   Manifest file is changed (new hash: 3298f1304...d4d421) or dependency folder (.aws-sam/deps/4d3dfad6-a267-47a6-a6cd-e07d6fae318c) is missing for (HelloWorldFunction), downloading dependencies and copying/building source
   Building codeuri: /Users/.../sam-app/hello_world runtime: python3.12 metadata: {} architecture: x86_64 functions: HelloWorldFunction
   Running PythonPipBuilder:CleanUp
   Running PythonPipBuilder:ResolveDependencies
   Running PythonPipBuilder:CopySource
   Running PythonPipBuilder:CopySource
   
   Build Succeeded
   
   Built Artifacts  : .aws-sam/build
   Built Template   : .aws-sam/build/template.yaml
   
   Commands you can use next
   =========================
   [*] Validate SAM template: sam validate
   [*] Invoke Function: sam local invoke
   [*] Test Function in the Cloud: sam sync --stack-name {{stack-name}} --watch
   [*] Deploy: sam deploy --guided
   ```

1.  AWS SAM CLI 會建立`.aws-sam`建置目錄。以下是範例：

   ```
   .aws-sam
   ├── build
   │   ├── HelloWorldFunction
   │   │   ├── __init__.py
   │   │   ├── app.py
   │   │   └── requirements.txt
   │   └── template.yaml
   └── build.toml
   ```

根據您的應用程式設定方式， AWS SAM CLI會執行下列動作：

1. 下載、安裝和組織 `.aws-sam/build`目錄中的相依性。

1. 準備您的 Lambda 程式碼。這可能包括編譯程式碼、建立可執行的二進位檔，以及建置容器映像。

1. 將建置成品複製到 `.aws-sam`目錄。格式會根據您的應用程式套件類型而有所不同。

   1. 對於 .zip 套件類型，成品尚未壓縮，因此可用於本機測試。使用 AWS SAM CLI時， 會壓縮您的應用程式`sam deploy`。

   1. 對於容器映像套件類型，容器映像會在本機建立，並在 `.aws-sam/build.toml` 檔案中參考。

1. 將 AWS SAM 範本複製到 `.aws-sam`目錄，並在必要時使用新的檔案路徑對其進行修改。

以下是組成 `.aws-sam`目錄中建置成品的主要元件：
+ **建置目錄 – **包含彼此獨立建構的 Lambda 函數和圖層。這會導致 `.aws-sam/build`目錄中每個函數或 layer 的唯一結構。
+ ** AWS SAM 範本** – 根據建置過程中的變更，以更新的值進行修改。
+ **build.toml 檔案** – 包含 所用建置設定的組態檔案 AWS SAM CLI。

## 本機測試和部署
<a name="using-sam-cli-build-test-deploy"></a>

使用 執行本機測試`sam local`或使用 部署時`sam deploy`， AWS SAM CLI會執行下列動作：

1. 它會先檢查 `.aws-sam`目錄是否存在，以及 AWS SAM 範本是否位於該目錄中。如果符合這些條件， AWS SAM CLI會將此視為應用程式的根目錄。

1. 如果不符合這些條件， AWS SAM CLI會將 AWS SAM 範本的原始位置視為應用程式的根目錄。

開發時，如果對原始應用程式檔案進行變更，請執行 `sam build` 以在本機測試之前更新`.aws-sam`目錄。

## 最佳實務
<a name="using-sam-cli-build-best"></a>
+ 請勿在 `.aws-sam/build`目錄下編輯任何程式碼。請改為更新專案資料夾中的原始原始原始程式碼，並執行 `sam build`以更新`.aws-sam/build`目錄。
+ 當您修改原始檔案時，請執行 `sam build`以更新`.aws-sam/build`目錄。
+ 您可能希望 AWS SAM CLI參考專案的原始根目錄，而不是 `.aws-sam`目錄，例如使用 進行開發和測試時`sam local`。刪除 `.aws-sam`目錄中的 目錄或 `.aws-sam`目錄中的 AWS SAM 範本，讓 將 AWS SAM CLI原始專案目錄辨識為根專案目錄。準備就緒時，請`sam build`再次執行 以建立`.aws-sam`目錄。
+ 當您執行 時`sam build`，每次都會覆寫`.aws-sam/build`目錄。`.aws-sam` 目錄不會。如果您想要存放日誌等檔案，請將它們存放在 中`.aws-sam`，以防止它們遭到覆寫。

## sam 建置的選項
<a name="using-sam-cli-build-options"></a>

### 建置單一資源
<a name="using-sam-cli-build-options-resource"></a>

提供資源的邏輯 ID，以僅建置該資源。以下是範例：

```
$ sam build HelloWorldFunction
```

若要建置巢狀應用程式或堆疊的資源，請使用 格式提供應用程式或堆疊邏輯 ID 以及資源邏輯 ID`<stack-logical-id>/<resource-logical-id>`：

```
$ sam build MyNestedStack/MyFunction
```

### 在提供的容器內建置 Lambda 函數
<a name="using-sam-cli-build-options-container"></a>

`--use-container` 選項會下載容器映像，並使用它來建置 Lambda 函數。接著會在您的 `.aws-sam/build.toml` 檔案中參考本機容器。

Docker 需要安裝此選項。如需說明，請參閱[安裝 Docker](install-docker.md)。

以下是此命令的範例：

```
$ sam build --use-container
```

您可以指定要與 `--build-image`選項搭配使用的容器映像。以下是範例：

```
$ sam build --use-container --build-image amazon/aws-sam-cli-build-image-nodejs20.x
```

若要指定用於單一函數的容器映像，請提供函數邏輯 ID。以下是範例：

```
$ sam build --use-container --build-image Function1=amazon/aws-sam-cli-build-image-python3.12
```

### 將環境變數傳遞至建置容器
<a name="using-sam-cli-build-options-env"></a>

使用 `--container-env-var`將環境變數傳遞至建置容器。以下是範例：

```
$ sam build --use-container --container-env-var Function1.GITHUB_TOKEN=<token1> --container-env-var GLOBAL_ENV_VAR=<global-token>
```

若要從檔案傳遞環境變數，請使用 `--container-env-var-file`選項。以下是範例：

```
$ sam build --use-container --container-env-var-file <env.json>
```

`env.json` 檔案的範例：

```
{
  "MyFunction1": {
    "GITHUB_TOKEN": "TOKEN1"
  },
  "MyFunction2": {
    "GITHUB_TOKEN": "TOKEN2"
  }
}
```

### 加速建置包含多個函數的應用程式
<a name="using-sam-cli-build-options-speed"></a>

當您在具有多個函數的應用程式`sam build`上執行 時， AWS SAM CLI會一次建立一個函數。若要加速建置程序，請使用 `--parallel`選項。這可同時建置所有函數和層。

以下是此命令的範例：

```
$ sam build —-parallel
```

### 在來源資料夾中建置您的專案，以加快建置時間
<a name="using-sam-cli-build-options-source"></a>

對於支援的執行時間和建置方法，您可以使用 `--build-in-source`選項直接在來源資料夾中建置專案。根據預設， 會在暫存目錄中 AWS SAM CLI建置，這涉及透過原始碼和專案檔案進行複製。使用 `--build-in-source`時， AWS SAM 會直接在您的來源資料夾中CLI建置，而不需要將檔案複製到暫時目錄，即可加速建置程序。

如需支援的執行時間和建置方法清單，請參閱 `--build-in-source`。

## 疑難排解
<a name="using-sam-cli-build-troubleshooting"></a>

若要疑難排解 AWS SAM CLI，請參閱 [AWS SAM CLI 故障診斷](sam-cli-troubleshooting.md)。

## 範例
<a name="using-sam-cli-build-examples"></a>

### 建置使用原生執行期和 .zip 套件類型的應用程式
<a name="using-sam-cli-build-examples-tutorial1"></a>

如需此範例，請參閱 [教學課程：使用 部署 Hello World 應用程式 AWS SAM](serverless-getting-started-hello-world.md)。

### 建置使用原生執行時間和映像套件類型的應用程式
<a name="using-sam-cli-build-examples-image"></a>

首先，我們會執行 `sam init` 來初始化新的應用程式。在互動式流程中，我們會選取`Image`套件類型。以下是範例：

```
$ sam init
...
Which template source would you like to use?
        1 - AWS Quick Start Templates
        2 - Custom Template Location
Choice: 1

Choose an AWS Quick Start application template
        1 - Hello World Example
        2 - Multi-step workflow
        3 - Serverless API
        4 - Scheduled task
        5 - Standalone function
        6 - Data processing
        7 - Hello World Example With Powertools
        8 - Infrastructure event management
        9 - Serverless Connector Hello World Example
        10 - Multi-step workflow with Connectors
        11 - Lambda EFS example
        12 - DynamoDB Example
        13 - Machine Learning
Template: 1

Use the most popular runtime and package type? (Python and zip) [y/N]: ENTER

Which runtime would you like to use?
        ...
        10 - java8
        11 - nodejs20.x
        12 - nodejs18.x
        13 - nodejs16.x
        ...
Runtime: 12

What package type would you like to use?
        1 - Zip
        2 - Image
Package type: 2

Based on your selections, the only dependency manager available is npm.
We will proceed copying the template using npm.

Would you like to enable X-Ray tracing on the function(s) in your application?  [y/N]: ENTER

Would you like to enable monitoring using CloudWatch Application Insights?
For more info, please view https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch-application-insights.html [y/N]: ENTER

Project name [sam-app]: ENTER

Cloning from https://github.com/aws/aws-sam-cli-app-templates (process may take a moment)

    -----------------------
    Generating application:
    -----------------------
    Name: sam-app
    Base Image: amazon/nodejs18.x-base
    Architectures: x86_64
    Dependency Manager: npm
    Output Directory: .
    Configuration file: sam-app/samconfig.toml

    Next steps can be found in the README file at sam-app/README.md
    
...
```

會 AWS SAM CLI初始化應用程式並建立下列專案目錄：

```
sam-app
├── README.md
├── events
│   └── event.json
├── hello-world
│   ├── Dockerfile
│   ├── app.mjs
│   ├── package.json
│   └── tests
│       └── unit
│           └── test-handler.mjs
├── samconfig.toml
└── template.yaml
```

接下來，我們會執行 `sam build`來建置應用程式：

```
sam-app $ sam build
Building codeuri: /Users/.../build-demo/sam-app runtime: None metadata: {'DockerTag': 'nodejs18.x-v1', 'DockerContext': '/Users/.../build-demo/sam-app/hello-world', 'Dockerfile': 'Dockerfile'} architecture: arm64 functions: HelloWorldFunction
Building image for HelloWorldFunction function
Setting DockerBuildArgs: {} for HelloWorldFunction function
Step 1/4 : FROM public.ecr.aws/lambda/nodejs:18
 ---> f5b68038c080
Step 2/4 : COPY app.mjs package*.json ./
 ---> Using cache
 ---> 834e565aae80
Step 3/4 : RUN npm install
 ---> Using cache
 ---> 31c2209dd7b5
Step 4/4 : CMD ["app.lambdaHandler"]
 ---> Using cache
 ---> 2ce2a438e89d
Successfully built 2ce2a438e89d
Successfully tagged helloworldfunction:nodejs18.x-v1

Build Succeeded

Built Artifacts  : .aws-sam/build
Built Template   : .aws-sam/build/template.yaml

Commands you can use next
=========================
[*] Validate SAM template: sam validate
[*] Invoke Function: sam local invoke
[*] Test Function in the Cloud: sam sync --stack-name {{stack-name}} --watch
[*] Deploy: sam deploy --guided
```

### 建置包含編譯程式設計語言的應用程式
<a name="using-sam-cli-build-examples-compiled"></a>

在此範例中，我們會建置應用程式，其中包含使用 Go 執行時間的 Lambda 函數。

首先，我們使用 初始化新的應用程式，`sam init`並將應用程式設定為使用 Go：

```
$ sam init

...

Which template source would you like to use?
        1 - AWS Quick Start Templates
        2 - Custom Template Location
Choice: 1

Choose an AWS Quick Start application template
        1 - Hello World Example
        2 - Multi-step workflow
        3 - Serverless API
        ...
Template: 1

Use the most popular runtime and package type? (Python and zip) [y/N]: ENTER

Which runtime would you like to use?
        ...
        4 - dotnetcore3.1
        5 - go1.x
        6 - go (provided.al2)
        ...
Runtime: 5

What package type would you like to use?
        1 - Zip
        2 - Image
Package type: 1

Based on your selections, the only dependency manager available is mod.
We will proceed copying the template using mod.

Would you like to enable X-Ray tracing on the function(s) in your application?  [y/N]: ENTER

Would you like to enable monitoring using CloudWatch Application Insights?
For more info, please view https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch-application-insights.html [y/N]: ENTER

Project name [sam-app]: ENTER

Cloning from https://github.com/aws/aws-sam-cli-app-templates (process may take a moment)

    -----------------------
    Generating application:
    -----------------------
    Name: sam-app
    Runtime: go1.x
    Architectures: x86_64
    Dependency Manager: mod
    Application Template: hello-world
    Output Directory: .
    Configuration file: sam-app/samconfig.toml
    
    Next steps can be found in the README file at sam-app-go/README.md
        
...
```

會 AWS SAM CLI初始化應用程式。以下是應用程式目錄結構的範例：

```
sam-app
├── Makefile
├── README.md
├── events
│   └── event.json
├── hello-world
│   ├── go.mod
│   ├── go.sum
│   ├── main.go
│   └── main_test.go
├── samconfig.toml
└── template.yaml
```

我們參考 `README.md` 檔案以滿足此應用程式的需求。

```
...
## Requirements
* AWS CLI already configured with Administrator permission
* [Docker installed](https://www.docker.com/community-edition)
* [Golang](https://golang.org)
* SAM CLI - [Install the SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html)
...
```

接下來，我們會執行 `sam local invoke` 來測試函數。Go 因為 未安裝在本機電腦上，所以此命令錯誤：

```
sam-app $ sam local invoke
Invoking hello-world (go1.x)
Local image was not found.
Removing rapid images for repo public.ecr.aws/sam/emulation-go1.x
Building image.................................................................................................................................................................................................................................................
Using local image: public.ecr.aws/lambda/go:1-rapid-x86_64.

Mounting /Users/.../Playground/build/sam-app/hello-world as /var/task:ro,delegated inside runtime container
START RequestId: c6c5eddf-042b-4e1e-ba66-745f7c86dd31 Version: $LATEST
fork/exec /var/task/hello-world: no such file or directory: PathError
null
END RequestId: c6c5eddf-042b-4e1e-ba66-745f7c86dd31
REPORT RequestId: c6c5eddf-042b-4e1e-ba66-745f7c86dd31  Init Duration: 0.88 ms  Duration: 175.75 ms Billed Duration: 176 ms Memory Size: 128 MB     Max Memory Used: 128 MB
{"errorMessage":"fork/exec /var/task/hello-world: no such file or directory","errorType":"PathError"}%
```

接下來，我們會執行 `sam build`來建置應用程式。我們遇到錯誤，因為 Go 未安裝在本機電腦上：

```
sam-app $ sam build
Starting Build use cache
Cache is invalid, running build and copying resources for following functions (HelloWorldFunction)
Building codeuri: /Users/.../Playground/build/sam-app/hello-world runtime: go1.x metadata: {} architecture: x86_64 functions: HelloWorldFunction

Build Failed
Error: GoModulesBuilder:Resolver - Path resolution for runtime: go1.x of binary: go was not successful
```

雖然我們可以設定本機機器以正確建置函數，但我們改為將 `--use-container`選項與 搭配使用`sam build`。會 AWS SAM CLI下載容器映像、使用原生 GoModulesBuilder 建置函數，並將產生的二進位檔複製到我們的`.aws-sam/build/HelloWorldFunction`目錄。

```
sam-app $ sam build --use-container
Starting Build use cache
Starting Build inside a container
Cache is invalid, running build and copying resources for following functions (HelloWorldFunction)
Building codeuri: /Users/.../build/sam-app/hello-world runtime: go1.x metadata: {} architecture: x86_64 functions: HelloWorldFunction

Fetching public.ecr.aws/sam/build-go1.x:latest-x86_64 Docker container image.....................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................
Mounting /Users/.../build/sam-app/hello-world as /tmp/samcli/source:ro,delegated inside runtime container
Running GoModulesBuilder:Build

Build Succeeded

Built Artifacts  : .aws-sam/build
Built Template   : .aws-sam/build/template.yaml

Commands you can use next
=========================
[*] Validate SAM template: sam validate
[*] Invoke Function: sam local invoke
[*] Test Function in the Cloud: sam sync --stack-name {{stack-name}} --watch
[*] Deploy: sam deploy --guided
```

以下是 `.aws-sam`目錄的範例：

```
.aws-sam
├── build
│   ├── HelloWorldFunction
│   │   └── hello-world
│   └── template.yaml
├── build.toml
├── cache
│   └── c860d011-4147-4010-addb-2eaa289f4d95
│       └── hello-world
└── deps
```

接下來，我們會執行 `sam local invoke`。我們的函數已成功調用：

```
sam-app $ sam local invoke
Invoking hello-world (go1.x)
Local image is up-to-date
Using local image: public.ecr.aws/lambda/go:1-rapid-x86_64.

Mounting /Users/.../Playground/build/sam-app/.aws-sam/build/HelloWorldFunction as /var/task:ro,delegated inside runtime container
START RequestId: cfc8ffa8-29f2-49d4-b461-45e8c7c80479 Version: $LATEST
END RequestId: cfc8ffa8-29f2-49d4-b461-45e8c7c80479
REPORT RequestId: cfc8ffa8-29f2-49d4-b461-45e8c7c80479  Init Duration: 1.20 ms  Duration: 1782.46 ms        Billed Duration: 1783 ms        Memory Size: 128 MB     Max Memory Used: 128 MB
{"statusCode":200,"headers":null,"multiValueHeaders":null,"body":"Hello, 72.21.198.67\n"}%
```

## 進一步了解
<a name="using-sam-cli-build-learn"></a>

若要進一步了解如何使用 `sam build`命令，請參閱以下內容：
+ **[學習 AWS SAM：sam build](https://www.youtube.com/watch?v=fDhYKp4op_g)** – 上的 Serverless Land "Learning AWS SAM" 系列YouTube。
+ **[Learning AWS SAM \$1 sam build \$1 E3 ](https://www.youtube.com/watch?v=vsAvRyLnB7Y)** – 上的 Serverless Land "Learning AWS SAM" 系列YouTube。
+ **[AWS SAM build：它如何為部署提供成品 （使用 SAM S2E8 的工作階段）](https://www.youtube.com/watch?v=bNbBd6XoDHg)** – 在 上具有 AWS SAM 序列的工作階段YouTube。
+ **[AWS SAM 自訂組建：如何使用 Makefiles 在 SAM (S2E9) 中自訂組建](https://www.youtube.com/watch?v=wpccutnSbAk)** – 在 上使用 AWS SAM 序列的工作階段YouTube。

# 使用 的預設建置 AWS SAM
<a name="serverless-sam-cli-using-build"></a>

若要建置無伺服器應用程式，請使用 `sam build`命令。此命令也會收集應用程式相依性的建置成品，並將其置於適當的格式和位置，以供後續步驟使用，例如本機測試、封裝和部署。

您可以在資訊清單檔案中指定應用程式的相依性，例如 `requirements.txt`(Python) 或 `package.json`(Node.js)，或使用函數資源的 `Layers` 屬性。`Layers` 屬性包含 Lambda 函數所依賴的[AWS Lambda 層](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html)資源清單。

應用程式建置成品的格式取決於每個函數的 `PackageType` 屬性。此屬性的選項為：
+ **`Zip`** – .zip 檔案封存，其中包含您的應用程式程式碼及其相依性。如果您將程式碼封裝為 .zip 檔案封存，則必須為函數指定 Lambda 執行時間。
+ **`Image`** – 容器映像，除了您的應用程式程式碼及其相依性之外，還包括基本作業系統、執行時間和擴充功能。

如需 Lambda 套件類型的詳細資訊，請參閱《 *AWS Lambda 開發人員指南*》中的 [Lambda 部署套件](https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-package.html)。

**Topics**
+ [建置 .zip 檔案封存](#build-zip-archive)
+ [建置容器映像](#build-container-image)
+ [容器環境變數檔案](#serverless-sam-cli-using-container-environment-file)
+ [在來源資料夾中建置您的專案，以加快建置時間](#serverless-sam-cli-using-build-in-source)
+ [範例](#building-applications-examples)
+ [在 外部建置 函數 AWS SAM](#building-applications-skip)

## 建置 .zip 檔案封存
<a name="build-zip-archive"></a>

若要將無伺服器應用程式建置為 .zip 檔案封存，`PackageType: Zip`請為無伺服器函數宣告 。

AWS SAM 會為您指定的[架構](sam-resource-function.md#sam-function-architectures)建置您的應用程式。如果您未指定 架構， `x86_64` 預設 AWS SAM 會使用 。

如果您的 Lambda 函數取決於具有原生編譯程式的套件，請使用 `--use-container`旗標。此旗標會在本機編譯容器中的函數，其行為類似於 Lambda 環境，因此當您將函數部署到 AWS 雲端時，其格式正確。

當您使用 `--use-container`選項時，預設會從 [Amazon ECR Public](https://docs.aws.amazon.com/AmazonECR/latest/public/what-is-ecr.html) AWS SAM 提取容器映像。如果您想要從另一個儲存庫或特定版本的 CLI AWS SAM 提取容器映像，您可以使用 `--build-image`選項並提供替代容器映像的 URI。以下是使用來自特定 CLI AWS SAM 版本之容器映像建置應用程式的兩個範例命令：

```
# Build a Node.js 20 application using a container image for a specific version of AWS SAM CLI (1.136.0)
sam build --use-container --build-image public.ecr.aws/sam/build-nodejs22.x:1.136.0

# Build a function resource using the Python 3.13 container image from a specific version of AWS SAM CLI (1.136.0)(
sam build --use-container --build-image Function1=public.ecr.aws/sam/build-python3.13:1.136.0
```

如需建置 .zip 檔案封存應用程式的其他範例，請參閱本主題稍後的範例一節。

## 建置容器映像
<a name="build-container-image"></a>

若要將無伺服器應用程式建置為容器映像，`PackageType: Image`請為無伺服器函數宣告 。您還必須使用下列項目宣告`Metadata`資源屬性：

`Dockerfile`  
與 Lambda 函數相關聯的 Dockerfile 名稱。

`DockerContext`  
Dockerfile 的位置。

`DockerTag`  
（選用） 要套用至建置映像的標籤。

`DockerBuildArgs`  
建置組建的引數。  
 AWS SAM CLI 不會修訂或混淆您在`DockerBuildArgs`引數中包含的任何資訊。我們強烈建議您不要使用此區段來儲存機密資訊，例如密碼或秘密。

以下是範例`Metadata`資源屬性區段：

```
    Metadata:
      Dockerfile: Dockerfile
      DockerContext: ./hello_world
      DockerTag: v1
```

若要下載使用 `Image`套件類型設定的範例應用程式，請參閱 [教學課程：使用 部署 Hello World 應用程式 AWS SAM](serverless-getting-started-hello-world.md)。在詢問您要安裝的套件類型的提示中，選擇 `Image`。

**注意**  
如果您在 Dockerfile 中指定多架構基礎映像， 會為主機機器的架構 AWS SAM 建置容器映像。若要為不同的架構建置 ，請指定使用特定目標架構的基礎映像。

## 容器環境變數檔案
<a name="serverless-sam-cli-using-container-environment-file"></a>

若要提供包含建置容器環境變數的 JSON 檔案，請使用 `--container-env-var-file`引數搭配 `sam build`命令。您可以提供套用至所有無伺服器資源的單一環境變數，或每個資源的不同環境變數。

### 格式
<a name="serverless-sam-cli-using-container-environment-file-format"></a>

將環境變數傳遞至建置容器的格式取決於您為 資源提供的環境變數數量。

若要為所有資源提供單一環境變數，請指定如下所示的`Parameters`物件：

```
{
  "Parameters": {
    "GITHUB_TOKEN": "TOKEN_GLOBAL"
  }
}
```

若要為每個資源提供不同的環境變數，請為每個資源指定物件，如下所示：

```
{
  "MyFunction1": {
    "GITHUB_TOKEN": "TOKEN1"
  },
  "MyFunction2": {
    "GITHUB_TOKEN": "TOKEN2"
  }
}
```

將您的環境變數儲存為 檔案，例如，名為 `env.json`。下列命令使用此檔案將環境變數傳遞至建置容器：

```
sam build --use-container --container-env-var-file env.json
```

### 優先順序
<a name="serverless-sam-cli-using-container-environment-file-precedence"></a>
+ 您提供給特定資源的環境變數優先於所有資源的單一環境變數。
+ 您在命令列提供的環境變數優先於檔案中的環境變數。

## 在來源資料夾中建置您的專案，以加快建置時間
<a name="serverless-sam-cli-using-build-in-source"></a>

對於支援的執行時間和建置方法，您可以使用 `--build-in-source`選項直接在來源資料夾中建置專案。根據預設， 會在暫存目錄中 AWS SAM CLI建置，這涉及透過原始程式碼和專案檔案進行複製。使用 `--build-in-source`時， AWS SAM 會直接在您的來源資料夾中CLI建置，而不需要將檔案複製到暫時目錄，即可加速建置程序。

如需支援的執行時間和建置方法清單，請參閱 `--build-in-source`。

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

### 範例 1：.zip 檔案封存
<a name="examples-zip-archives"></a>

下列`sam build`命令會建置 .zip 檔案封存：

```
# Build all functions and layers, and their dependencies
sam build

# Run the build process inside a Docker container that functions like a Lambda environment
sam build --use-container

# Build a Node.js 20 application using a container image for a specific version of AWS SAM CLI (1.136.0)
sam build --use-container --build-image public.ecr.aws/sam/build-nodejs22.x:1.136.0

# Build a function resource using the Python 3.13 container image from a specific version of AWS SAM CLI (1.136.0)(
sam build --use-container --build-image Function1=public.ecr.aws/sam/build-python3.13:1.136.0

# Build and run your functions locally
sam build && sam local invoke

# For more options
sam build --help
```

### 範例 2：容器映像
<a name="examples-container-image-1"></a>

下列 AWS SAM 範本建置為容器映像：

```
Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      PackageType: Image
      ImageConfig:
        Command: ["app.lambda_handler"]
    Metadata:
      Dockerfile: Dockerfile
      DockerContext: ./hello_world
      DockerTag: v1
```

以下是 Dockerfile 範例：

```
FROM public.ecr.aws/lambda/python:3.12

COPY app.py requirements.txt ./

RUN python3.12 -m pip install -r requirements.txt

# Overwrite the command by providing a different command directly in the template.
CMD ["app.lambda_handler"]
```

### 範例 3：npm ci
<a name="examples-npm-ci"></a>

對於 Node.js 應用程式，您可以使用 `npm ci`而不是 `npm install` 安裝相依性。若要使用 `npm ci`，請在 Lambda 函數`Metadata`的資源屬性`BuildProperties`中指定 `UseNpmCi: True` 下的 。若要使用 `npm ci`，您的應用程式必須在 Lambda 函數`CodeUri`的 中具有 `package-lock.json`或 `npm-shrinkwrap.json` 檔案。

當您執行 時`npm ci`，下列範例會使用 安裝相依性`sam build`：

```
Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: hello-world/
      Handler: app.handler
      Runtime: nodejs20.x
      Architectures:
        - x86_64
      Events:
        HelloWorld:
          Type: Api
          Properties:
            Path: /hello
            Method: get
    Metadata:
      BuildProperties:
        UseNpmCi: True
```

### Python 父系套件
<a name="building-applications-python-parent-packages"></a>

對於 Python 應用程式，您可以在建置過程中保留套件結構，以啟用絕對匯入。若要保留套件結構，請在 Lambda 函數`Metadata`的資源屬性`BuildProperties`中指定 `ParentPackageMode` 下的 。

當您執行 時，下列範例會保留`app`套件結構`sam build`：

```
Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: hello-world/
      Handler: app.main.handler
      Runtime: python3.12
      Architectures:
        - x86_64
    Metadata:
      BuildProperties:
        ParentPackageMode: explicit
        ParentPackages: app
```

透過此組態，您的程式碼可以使用 等絕對匯入`from app.utils import logger`，而不是 等相對匯入`from .utils import logger`。

## 在 外部建置 函數 AWS SAM
<a name="building-applications-skip"></a>

根據預設，當您執行 時**sam build**， 會 AWS SAM 建置您的所有函數資源。其他選項包括：
+ **在 之外建置所有函數資源 AWS SAM** – 如果您手動或透過其他工具建置所有函數資源，**sam build**則不需要 。您可以略過**sam build**並繼續進行程序的下一個步驟，例如執行本機測試或部署應用程式。
+ 在 **外部建置一些函數資源 AWS SAM** – 如果您想要在外部建置其他函數資源的同時 AWS SAM 建置一些函數資源 AWS SAM，您可以在 AWS SAM 範本中指定此選項。

### 在 外部建置一些函數資源 AWS SAM
<a name="building-applications-skip-some"></a>

若要在使用 時 AWS SAM 略過函數**sam build**，請在 AWS SAM 範本中設定下列項目：

1. 將`SkipBuild: True`中繼資料屬性新增至函數。

1. 指定建置函數資源的路徑。

以下是範例，其中 `TestFunction`設定為略過。其建置的資源位於 `built-resources/TestFunction.zip`。

```
TestFunction:
  Type: AWS::Serverless::Function
  Properties:
    CodeUri: built-resources/TestFunction.zip
    Handler: TimeHandler::handleRequest
    Runtime: java11
  Metadata:
    SkipBuild: True
```

現在，當您執行 時**sam build**， AWS SAM 會執行下列動作：

1. AWS SAM 會略過使用 設定的函數`SkipBuild: True`。

1. AWS SAM 會建置所有其他函數資源，並將其快取在`.aws-sam`建置目錄中。

1. 對於略過的函數，其在`.aws-sam`建置目錄中的範本會自動更新，以參考所建置函數資源的指定路徑。

   以下是`TestFunction``.aws-sam`建置目錄中 的快取範本範例：

   ```
   TestFunction:
     Type: AWS::Serverless::Function
     Properties:
       CodeUri: ../../built-resources/TestFunction.zip
       Handler: TimeHandler::handleRequest
       Runtime: java11
     Metadata:
       SkipBuild: True
   ```

# 使用 自訂組建 AWS SAM
<a name="building-lambda-functions"></a>

您可以自訂建置以包含特定 Lambda 函數或 Lambda 層。函數是您可以叫用以在 Lambda 中執行程式碼的資源。Lambda 層可讓您從 Lambda 函數擷取程式碼，然後在多個 Lambda 函數之間重複使用。當您想要專注於開發和部署個別的無伺服器函數，而無需管理共用相依性或資源的複雜性時，可以選擇使用特定 Lambda 函數自訂您的建置。此外，您可以選擇建置 Lambda 層，以協助您減少部署套件的大小、將核心函數邏輯與相依性分開，以及讓您在多個函數之間共用相依性。

本節中的主題會探索您可以使用的一些不同方式來建置 Lambda 函數 AWS SAM。這包括使用客戶執行時間建置 Lambda 函數，以及建置 Lambda 層。《 AWS Lambda 開發人員指南》中的自訂執行階段可讓您安裝和使用 Lambda 執行階段中未列出的語言。這可讓您建立專用執行環境，以執行無伺服器函數和應用程式。僅建置 Lambda 層 （而不是建置整個應用程式） 可以透過幾種方式使您受益。它可協助您減少部署套件的大小、將核心函數邏輯與相依性分開，並允許您在多個函數之間共用相依性。

如需 函數的詳細資訊，請參閱《 *AWS Lambda 開發人員指南*》中的 [Lambda 概念](https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-concepts.html)。

**Topics**
+ [在 中使用 esbuild 建置 Node.js Lambda 函數 AWS SAM](serverless-sam-cli-using-build-typescript.md)
+ [在 中使用原生 AOT 編譯建置 .NET Lambda 函數 AWS SAM](build-dotnet7.md)
+ [在 Cargo Lambda中使用 建置 Rust Lambda 函數 AWS SAM](building-rust.md)
+ [在 uv中使用 建置 Python Lambda 函數 AWS SAM](building-python-uv.md)
+ [在 中使用自訂執行期建置 Lambda 函數 AWS SAM](building-custom-runtimes.md)
+ [在 中建置 Lambda 層 AWS SAM](building-layers.md)

# 在 中使用 esbuild 建置 Node.js Lambda 函數 AWS SAM
<a name="serverless-sam-cli-using-build-typescript"></a>

若要建置和封裝 Node.js AWS Lambda 函數，您可以使用 AWS SAM CLI搭配 esbuild JavaScript bundler。esbuild bundler 支援您在 TypeScript 中寫入的 Lambda 函數。

若要使用 esbuild 建置 Node.js Lambda 函數，請將`Metadata`物件新增至您的`AWS:Serverless::Function`資源，並為 指定 `esbuild` `BuildMethod`。當您執行 **sam build**命令時， AWS SAM 會使用 esbuild 來綁定 Lambda 函數程式碼。

## 中繼資料屬性
<a name="serverless-sam-cli-using-build-typescript-metadata"></a>

`Metadata` 物件支援 esbuild 的下列屬性。

### BuildMethod
<a name="serverless-sam-cli-using-build-typescript-metadata-buildmethod"></a>

為您的應用程式指定 Bundler。唯一支援的值為 `esbuild`。

### BuildProperties
<a name="serverless-sam-cli-using-build-typescript-metadata-buildproperties"></a>

指定 Lambda 函數程式碼的建置屬性。

`BuildProperties` 物件支援 esbuild 的下列屬性。所有屬性都是選用的。根據預設， AWS SAM 會將 Lambda 函數處理常式用於進入點。

**EntryPoints**  
為您的應用程式指定進入點。

**外部**  
指定要從建置中省略的套件清單。如需詳細資訊，請參閱 *esbuild 網站的*[外部](https://esbuild.github.io/api/#external)。

**格式**  
指定應用程式中產生的 JavaScript 檔案的輸出格式。如需詳細資訊，請參閱 *esbuild 網站上的*[格式化](https://esbuild.github.io/api/#format)。

**載入器**  
指定用於載入指定檔案類型之資料的組態清單。

**MainFields**  
指定解析套件時要嘗試匯入`package.json`的欄位。預設值為 `main,module`。

**Minify**  
指定是否將綁定的輸出程式碼縮小。預設值為 `true`。

**OutExtension**  
自訂 esbuild 產生的檔案副檔名。如需詳細資訊，請參閱 *esbuild 網站上的* [Out 擴充](https://esbuild.github.io/api/#out-extension)功能。

**來源映射**  
指定 Bundler 是否產生來源映射檔案。預設值為 `false`。  
設定為 時`true`， `NODE_OPTIONS: --enable-source-maps` 會附加到 Lambda 函數的環境變數，並產生來源映射並包含在函數中。  
或者，當 `NODE_OPTIONS: --enable-source-maps` 包含在函數的環境變數中時， `Sourcemap` 會自動設定為 `true`。  
衝突時， `Sourcemap: false` 優先於 `NODE_OPTIONS: --enable-source-maps`。  
根據預設，Lambda 會使用 AWS Key Management Service () 加密所有靜態環境變數AWS KMS。使用來源映射時，為了讓部署成功，函數的執行角色必須具有執行 `kms:Encrypt`動作的許可。

**SourcesContent**  
指定是否要在來源映射檔案中包含您的原始程式碼。當 設定為 時`Sourcemap`，設定此屬性`'true'`。  
+ 指定 `SourcesContent: 'true'`以包含所有原始程式碼。
+ 指定 `SourcesContent: 'false'`以排除所有原始程式碼。這會導致來源映射檔案大小變小，這可透過縮短啟動時間在生產環境中很有用。不過，偵錯工具中無法使用原始程式碼。
預設值為 `SourcesContent: true`。  
如需詳細資訊，請參閱 *esbuild 網站上的*[來源內容](https://esbuild.github.io/api/#sources-content)。

**Target**  
指定目標 ECMAScript 版本。預設值為 `es2020`。

## TypeScript Lambda 函數範例
<a name="serverless-sam-cli-using-build-typescript-example"></a>

下列範例 AWS SAM 範本程式碼片段使用 esbuild 從 中的 TypeScript 程式碼建立 Node.js Lambda 函數`hello-world/app.ts`。

```
Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: hello-world/
      Handler: app.handler
      Runtime: nodejs20.x
      Architectures:
        - x86_64
      Events:
        HelloWorld:
          Type: Api 
          Properties:
            Path: /hello
            Method: get
      Environment:
        Variables:
          NODE_OPTIONS: --enable-source-maps
    Metadata:
      BuildMethod: esbuild
      BuildProperties:
        Format: esm
        Minify: false
        OutExtension:
          - .js=.mjs
        Target: "es2020"
        Sourcemap: true
        EntryPoints: 
          - app.ts
        External:
          - "<package-to-exclude>"
```

# 在 中使用原生 AOT 編譯建置 .NET Lambda 函數 AWS SAM
<a name="build-dotnet7"></a>

使用 AWS Serverless Application Model (AWS SAM) 建置並封裝您的 .NET 8 AWS Lambda 函數，利用原生Ahead-of-Time(AOT) 編譯來改善 AWS Lambda 冷啟動時間。

**Topics**
+ [.NET 8 原生 AOT 概觀](#build-dotnet7-overview)
+ [AWS SAM 搭配 .NET 8 Lambda 函數使用](#build-dotnet7-sam)
+ [安裝先決條件](#build-dotnet7-prerequisites)
+ [在 AWS SAM 範本中定義 .NET 8 Lambda 函數](#build-dotnet7-sam-define)
+ [使用 建置您的應用程式 AWS SAM CLI](#build-dotnet7-sam-build)
+ [進一步了解](#build-dotnet7-learn-more)

## .NET 8 原生 AOT 概觀
<a name="build-dotnet7-overview"></a>

過去，.NET Lambda 函數的冷啟動時間會影響無伺服器應用程式的使用者體驗、系統延遲和使用成本。透過 .NET 原生 AOT 編譯，您可以改善 Lambda 函數的冷啟動時間。若要進一步了解適用於 .NET 8 的原生 AOT，請參閱 *Dotnet GitHub 儲存庫*中的[使用原生 AOT](https://github.com/dotnet/runtime/tree/main/src/coreclr/nativeaot#readme)。

## AWS SAM 搭配 .NET 8 Lambda 函數使用
<a name="build-dotnet7-sam"></a>

執行下列動作以使用 () 設定 .NET 8 Lambda AWS Serverless Application Model 函數AWS SAM：
+ 在開發機器上安裝先決條件。
+ 在 AWS SAM 範本中定義 .NET 8 Lambda 函數。
+ 使用 建置您的應用程式 AWS SAM CLI。

## 安裝先決條件
<a name="build-dotnet7-prerequisites"></a>

以下是必要的先決條件：
+ 的 AWS SAM CLI
+ .NET Core CLI
+ Amazon.Lambda.Tools .NET Core 全球工具
+ Docker

**安裝 AWS SAM CLI**

1. 若要檢查是否已安裝 AWS SAM CLI，請執行下列動作：

   ```
   sam --version
   ```

1. 若要安裝 AWS SAM CLI，請參閱 [安裝 AWS SAM CLI](install-sam-cli.md)。

1. 若要升級已安裝版本的 AWS SAM CLI，請參閱 [升級 AWS SAM CLI](manage-sam-cli-versions.md#manage-sam-cli-versions-upgrade)。

**安裝 .NET Core CLI**

1. 若要下載並安裝 .NET Core CLI，請參閱從 Microsoft [網站下載 .NET](https://dotnet.microsoft.com/download)。

1. 如需 .NET Core CLI 的詳細資訊，請參閱《 *AWS Lambda 開發人員指南*》中的 .[NET Core CLI](https://docs.aws.amazon.com/lambda/latest/dg/csharp-package-cli.html)。

**安裝 Amazon.Lambda.Tools .NET Core Global Tool**

1. 執行以下命令：

   ```
   dotnet tool install -g Amazon.Lambda.Tools
   ```

1. 如果您已安裝此工具，您可以使用以下命令，確保使用的是最新版本。

   ```
   dotnet tool update -g Amazon.Lambda.Tools
   ```

1. 如需有關 Amazon.Lambda.Tools .NET Core Global Tool 的詳細資訊，請參閱 GitHub 上的 [.NET CLI 儲存庫的AWS 延伸項目](https://github.com/aws/aws-extensions-for-dotnet-cli)。

**安裝 Docker**
+ 使用原生 AOT 建置 Docker需要安裝。如需安裝指示，請參閱[安裝 Docker 以搭配 使用 AWS SAM CLI](install-docker.md)。

## 在 AWS SAM 範本中定義 .NET 8 Lambda 函數
<a name="build-dotnet7-sam-define"></a>

若要在 AWS SAM 範本中定義 .NET8 Lambda 函數，請執行下列動作：

1. 從您選擇的開始目錄執行下列命令：

   ```
   sam init
   ```

1. 選取 `AWS Quick Start Templates` 以選擇啟動範本。

1. 選擇 `Hello World Example` 範本。

1. 輸入 以選擇不使用最熱門的執行時間和套件類型`n`。

1. 針對執行時間，選擇 `dotnet8`。

1. 針對套件類型，選擇 `Zip`。

1. 針對您的入門範本，選擇 `Hello World Example using native AOT`。

**安裝 Docker**
+ 使用原生 AOT 建置 Docker需要安裝。如需安裝指示，請參閱[安裝 Docker 以搭配 使用 AWS SAM CLI](install-docker.md)。

```
Resources:
HelloWorldFunction:
  Type: AWS::Serverless::Function
  Properties:
    CodeUri: ./src/HelloWorldAot/
    Handler: bootstrap
    Runtime: dotnet8
    Architectures:
      - x86_64
    Events:
      HelloWorldAot:
        Type: Api 
        Properties:
          Path: /hello
          Method: get
```

**注意**  
當 的 `Event` 屬性`AWS::Serverless::Function`設定為 `Api`，但未指定 `RestApiId` 屬性時， AWS SAM 會產生 `AWS::ApiGateway::RestApi` CloudFormation 資源。

## 使用 建置您的應用程式 AWS SAM CLI
<a name="build-dotnet7-sam-build"></a>

 從專案的根目錄中，執行 `sam build`命令以開始建置您的應用程式。如果您的 .NET 8 專案檔案中已定義 `PublishAot` 屬性，則 AWS SAM CLI將使用原生 AOT 編譯建置。若要進一步了解 `PublishAot` 屬性，請參閱 Microsoft .*NET 文件*中的[原生 AOT 部署](https://learn.microsoft.com/en-us/dotnet/core/deploying/native-aot/)。

若要建置函數， AWS SAM CLI會叫用使用 Amazon.Lambda.Tools .NET Core Global Tool 的 .NET Core CLI。

**注意**  
建置時，如果`.sln`檔案存在於您專案的相同或父目錄中，則包含該`.sln`檔案的目錄將掛載到容器。如果找不到`.sln`檔案，則只會掛載專案資料夾。因此，如果您要建置多專案應用程式，請確保`.sln`檔案位於 屬性。

## 進一步了解
<a name="build-dotnet7-learn-more"></a>

如需建置 .NET 8 Lambda 函數的詳細資訊，請參閱 [的 .NET 8 執行時間簡介 AWS Lambda](https://aws.amazon.com/blogs/compute/introducing-the-net-8-runtime-for-aws-lambda/)。

如需 **sam build**命令的參考，請參閱 [sam build](sam-cli-command-reference-sam-build.md)。

# 在 Cargo Lambda中使用 建置 Rust Lambda 函數 AWS SAM
<a name="building-rust"></a>


|  | 
| --- |
| 此功能目前為 的預覽版本 AWS SAM ，可能會有所變更。 | 

使用 AWS Serverless Application Model 命令列界面 (AWS SAM CLI) 搭配 Rust AWS Lambda 函數。

**Topics**
+ [先決條件](#building-rust-prerequisites)
+ [設定 AWS SAM 搭配 Rust Lambda 函數使用](#building-rust-configure)
+ [範例](#building-rust-examples)

## 先決條件
<a name="building-rust-prerequisites"></a>

**Rust 語言**  
若要安裝 Rust，請參閱*Rust語言網站*中的[安裝Rust](https://www.rust-lang.org/tools/install)。

**Cargo Lambda**  
 AWS SAM CLI 需要安裝 [https://www.cargo-lambda.info/guide/what-is-cargo-lambda.html](https://www.cargo-lambda.info/guide/what-is-cargo-lambda.html)，這是 的子命令Cargo。如需安裝說明，請參閱 *Cargo Lambda 文件*中的[安裝](https://www.cargo-lambda.info/guide/installation.html)。

**Docker**  
建置和測試 Rust Lambda 函數需要 Docker。如需安裝指示，請參閱[安裝 Docker](install-docker.md)。

**選擇加入 AWS SAM CLI Beta 版功能**  
由於此功能處於預覽狀態，您必須使用下列其中一種方法選擇加入：  

1. 使用環境變數：`SAM_CLI_BETA_RUST_CARGO_LAMBDA=1`。

1. 將以下內容新增到您的 `samconfig.toml` 檔案：

   ```
   [default.build.parameters]
   beta_features = true
   [default.sync.parameters]
   beta_features = true
   ```

1. 使用支援的 AWS SAM CLI命令時，請使用 `--beta-features`選項。例如：

   ```
   $ sam build --beta-features
   ```

1. 當 提示您選擇加入`y`時 AWS SAM CLI，請選擇選項。以下是範例：

   ```
   $ sam build
   Starting Build use cache
   Build method "rust-cargolambda" is a beta feature.
   Please confirm if you would like to proceed
   You can also enable this beta feature with "sam build --beta-features". [y/N]: y
   ```

## 設定 AWS SAM 搭配 Rust Lambda 函數使用
<a name="building-rust-configure"></a>

### 步驟 1：設定您的 AWS SAM 範本
<a name="building-rust-configure-template"></a>

使用下列項目設定您的 AWS SAM 範本：
+ **二進位** – 選用。指定您的範本何時包含多個 Rust Lambda 函數。
+ **BuildMethod** – `rust-cargolambda`。
+ **CodeUri** – `Cargo.toml` 檔案的路徑。
+ **處理常**式 – `bootstrap`。
+ **執行時間** – `provided.al2`。

若要進一步了解自訂執行期，請參閱《 *AWS Lambda 開發人員指南*》中的[自訂 AWS Lambda 執行期](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-custom.html)。

以下是已設定 AWS SAM 範本的範例：

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
...
Resources:
  MyFunction:
    Type: AWS::Serverless::Function
    Metadata:
      BuildMethod: rust-cargolambda
      BuildProperties: function_a
    Properties:
      CodeUri: ./rust_app
      Handler: bootstrap
      Runtime: provided.al2
...
```

### 步驟 2：搭配 Rust Lambda 函數使用 AWS SAM CLI
<a name="building-rust-configure-cli"></a>

將任何 AWS SAM CLI命令與 AWS SAM 範本搭配使用。如需詳細資訊，請參閱[AWS SAM CLI](using-sam-cli.md)。

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

### Hello World 範例
<a name="building-rust-examples-hello"></a>

**在此範例中，我們使用 Rust做為執行時間來建置範例 Hello World 應用程式。**

首先，我們使用 初始化新的無伺服器應用程式`sam init`。在互動式流程中，我們會選取 **Hello World 應用程式**，然後選擇 **Rust** 執行時間。

```
$ sam init
...
Which template source would you like to use?
        1 - AWS Quick Start Templates
        2 - Custom Template Location
Choice: 1

Choose an AWS Quick Start application template
        1 - Hello World Example
        2 - Multi-step workflow
        3 - Serverless API
        ...
Template: 1

Use the most popular runtime and package type? (Python and zip) [y/N]: ENTER

Which runtime would you like to use?
        1 - dotnet8
        2 - dotnet6
        3 - go (provided.al2)
        ...
        18 - python3.11
        19 - python3.10
        20 - ruby3.3
        21 - ruby3.2
        22 - rust (provided.al2)
        23 - rust (provided.al2023)
Runtime: 22

Based on your selections, the only Package type available is Zip.
We will proceed to selecting the Package type as Zip.

Based on your selections, the only dependency manager available is cargo.
We will proceed copying the template using cargo.

Would you like to enable X-Ray tracing on the function(s) in your application?  [y/N]: ENTER

Would you like to enable monitoring using CloudWatch Application Insights?
For more info, please view https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch-application-insights.html [y/N]: ENTER

Project name [sam-app]: hello-rust

    -----------------------
    Generating application:
    -----------------------
    Name: hello-rust
    Runtime: rust (provided.al2)
    Architectures: x86_64
    Dependency Manager: cargo
    Application Template: hello-world
    Output Directory: .
    Configuration file: hello-rust/samconfig.toml
    
    Next steps can be found in the README file at hello-rust/README.md
        

Commands you can use next
=========================
[*] Create pipeline: cd hello-rust && sam pipeline init --bootstrap
[*] Validate SAM template: cd hello-rust && sam validate
[*] Test Function in the Cloud: cd hello-rust && sam sync --stack-name {stack-name} --watch
```

以下是 Hello World 應用程式的結構：

```
hello-rust
├── README.md
├── events
│   └── event.json
├── rust_app
│   ├── Cargo.toml
│   └── src
│       └── main.rs
├── samconfig.toml
└── template.yaml
```

在我們的 AWS SAM 範本中，我們的Rust函數定義如下：

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
...
Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function 
    Metadata:
      BuildMethod: rust-cargolambda 
    Properties:
      CodeUri: ./rust_app 
      Handler: bootstrap   
      Runtime: provided.al2
      Architectures:
        - x86_64
      Events:
        HelloWorld:
          Type: Api
            Path: /hello
            Method: get
```

接下來，我們會執行 `sam build`來建置應用程式並準備部署。 AWS SAM CLI 會建立`.aws-sam`目錄，並在其中組織我們的建置成品。我們的函數是使用 建置，Cargo Lambda並存放在 做為可執行的二進位檔`.aws-sam/build/HelloWorldFunction/bootstrap`。

**注意**  
如果您打算在 MacOS 中執行 **sam local invoke**命令，則需要在叫用之前建置不同的函數。若要執行此作業，請使用下列命令：  
**SAM\$1BUILD\$1MODE=debug sam build**
只有在完成本機測試時，才需要此命令。建置 以進行部署時，不建議這麼做。

```
hello-rust$ sam build
Starting Build use cache
Build method "rust-cargolambda" is a beta feature.
Please confirm if you would like to proceed
You can also enable this beta feature with "sam build --beta-features". [y/N]: y

Experimental features are enabled for this session.
Visit the docs page to learn more about the AWS Beta terms https://aws.amazon.com/service-terms/.

Cache is invalid, running build and copying resources for following functions (HelloWorldFunction)
Building codeuri: /Users/.../hello-rust/rust_app runtime: provided.al2 metadata: {'BuildMethod': 'rust-cargolambda'} architecture: x86_64 functions: HelloWorldFunction
Running RustCargoLambdaBuilder:CargoLambdaBuild
Running RustCargoLambdaBuilder:RustCopyAndRename

Build Succeeded

Built Artifacts  : .aws-sam/build
Built Template   : .aws-sam/build/template.yaml

Commands you can use next
=========================
[*] Validate SAM template: sam validate
[*] Invoke Function: sam local invoke
[*] Test Function in the Cloud: sam sync --stack-name {{stack-name}} --watch
[*] Deploy: sam deploy --guided
```

接著，我們使用 部署應用程式`sam deploy --guided`。

```
hello-rust$ sam deploy --guided

Configuring SAM deploy
======================

        Looking for config file [samconfig.toml] :  Found
        Reading default arguments  :  Success

        Setting default arguments for 'sam deploy'
        =========================================
        Stack Name [hello-rust]: ENTER
        AWS Region [us-west-2]: ENTER
        #Shows you resources changes to be deployed and require a 'Y' to initiate deploy
        Confirm changes before deploy [Y/n]: ENTER
        #SAM needs permission to be able to create roles to connect to the resources in your template
        Allow SAM CLI IAM role creation [Y/n]: ENTER
        #Preserves the state of previously provisioned resources when an operation fails
        Disable rollback [y/N]: ENTER
        HelloWorldFunction may not have authorization defined, Is this okay? [y/N]: y
        Save arguments to configuration file [Y/n]: ENTER
        SAM configuration file [samconfig.toml]: ENTER
        SAM configuration environment [default]: ENTER

        Looking for resources needed for deployment:

        ...

        Uploading to hello-rust/56ba6585d80577dd82a7eaaee5945c0b  817973 / 817973  (100.00%)

        Deploying with following values
        ===============================
        Stack name                   : hello-rust
        Region                       : us-west-2
        Confirm changeset            : True
        Disable rollback             : False
        Deployment s3 bucket         : aws-sam-cli-managed-default-samclisam-s3-demo-bucket-1a4x26zbcdkqr
        Capabilities                 : ["CAPABILITY_IAM"]
        Parameter overrides          : {}
        Signing Profiles             : {}

Initiating deployment
=====================

        Uploading to hello-rust/a4fc54cb6ab75dd0129e4cdb564b5e89.template  1239 / 1239  (100.00%)


Waiting for changeset to be created..

CloudFormation stack changeset
---------------------------------------------------------------------------------------------------------
Operation                  LogicalResourceId          ResourceType               Replacement              
---------------------------------------------------------------------------------------------------------
+ Add                      HelloWorldFunctionHelloW   AWS::Lambda::Permission    N/A                      
                           orldPermissionProd                                                             
...                    
---------------------------------------------------------------------------------------------------------

Changeset created successfully. arn:aws:cloudformation:us-west-2:012345678910:changeSet/samcli-deploy1681427201/f0ef1563-5ab6-4b07-9361-864ca3de6ad6


Previewing CloudFormation changeset before deployment
======================================================
Deploy this changeset? [y/N]: y

2023-04-13 13:07:17 - Waiting for stack create/update to complete

CloudFormation events from stack operations (refresh every 5.0 seconds)
---------------------------------------------------------------------------------------------------------
ResourceStatus             ResourceType               LogicalResourceId          ResourceStatusReason     
---------------------------------------------------------------------------------------------------------
CREATE_IN_PROGRESS         AWS::IAM::Role             HelloWorldFunctionRole     -                        
CREATE_IN_PROGRESS         AWS::IAM::Role             HelloWorldFunctionRole     Resource creation        
...
---------------------------------------------------------------------------------------------------------

CloudFormation outputs from deployed stack
---------------------------------------------------------------------------------------------------------
Outputs                                                                                                 
---------------------------------------------------------------------------------------------------------
Key                 HelloWorldFunctionIamRole                                                           
Description         Implicit IAM Role created for Hello World function                                  
Value               arn:aws:iam::012345678910:role/hello-rust-HelloWorldFunctionRole-10II2P13AUDUY      

Key                 HelloWorldApi                                                                       
Description         API Gateway endpoint URL for Prod stage for Hello World function                    
Value               https://ggdxec9le9.execute-api.us-west-2.amazonaws.com/Prod/hello/                  

Key                 HelloWorldFunction                                                                  
Description         Hello World Lambda Function ARN                                                     
Value               arn:aws:lambda:us-west-2:012345678910:function:hello-rust-HelloWorldFunction-       
yk4HzGzYeZBj                                                                                            
---------------------------------------------------------------------------------------------------------


Successfully created/updated stack - hello-rust in us-west-2
```

若要測試，我們可以使用 API 端點叫用 Lambda 函數。

```
$ curl https://ggdxec9le9.execute-api.us-west-2.amazonaws.com/Prod/hello/
Hello World!%
```

若要在本機測試函數，首先我們會確保函數的`Architectures`屬性符合本機機器。

```
...
Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Metadata:
      BuildMethod: rust-cargolambda # More info about Cargo Lambda: https://github.com/cargo-lambda/cargo-lambda
    Properties:
      CodeUri: ./rust_app   # Points to dir of Cargo.toml
      Handler: bootstrap    # Do not change, as this is the default executable name produced by Cargo Lambda
      Runtime: provided.al2
      Architectures:
        - arm64
...
```

由於我們在此範例中`arm64`將架構從 修改`x86_64`為 ，因此我們執行 `sam build`來更新建置成品。然後，我們會執行 `sam local invoke`以本機叫用函數。

```
hello-rust$ sam local invoke
Invoking bootstrap (provided.al2)
Local image was not found.
Removing rapid images for repo public.ecr.aws/sam/emulation-provided.al2
Building image.....................................................................................................................................
Using local image: public.ecr.aws/lambda/provided:al2-rapid-arm64.

Mounting /Users/.../hello-rust/.aws-sam/build/HelloWorldFunction as /var/task:ro,delegated, inside runtime container
START RequestId: fbc55e6e-0068-45f9-9f01-8e2276597fc6 Version: $LATEST
{"statusCode":200,"body":"Hello World!"}END RequestId: fbc55e6e-0068-45f9-9f01-8e2276597fc6
REPORT RequestId: fbc55e6e-0068-45f9-9f01-8e2276597fc6  Init Duration: 0.68 ms  Duration: 130.63 ms     Billed Duration: 131 ms     Memory Size: 128 MB     Max Memory Used: 128 MB
```

### 單一 Lambda 函數專案
<a name="building-rust-examples-single"></a>

**以下是包含一個 Rust Lambda 函數的無伺服器應用程式範例。 **

專案目錄結構：

```
.
├── Cargo.lock
├── Cargo.toml
├── src
│   └── main.rs
└── template.yaml
```

AWS SAM 範本：

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
...
Resources:
  MyFunction:
    Type: AWS::Serverless::Function
    Metadata:
      BuildMethod: rust-cargolambda
    Properties:
      CodeUri: ./             
      Handler: bootstrap
      Runtime: provided.al2
...
```

### 多個 Lambda 函數專案
<a name="building-rust-examples-multiple"></a>

**以下是包含多個 Rust Lambda 函數的無伺服器應用程式範例。**

專案目錄結構：

```
.
├── Cargo.lock
├── Cargo.toml
├── src
│   ├── function_a.rs
│   └── function_b.rs
└── template.yaml
```

AWS SAM 範本：

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
...
Resources:
  FunctionA:
    Type: AWS::Serverless::Function
    Metadata:
      BuildMethod: rust-cargolambda
      BuildProperties:
        Binary: function_a 
    Properties:
      CodeUri: ./           
      Handler: bootstrap     
      Runtime: provided.al2
  FunctionB:
    Type: AWS::Serverless::Function
    Metadata:
      BuildMethod: rust-cargolambda
      BuildProperties:
        Binary: function_b
    Properties:
      CodeUri: ./
      Handler: bootstrap
      Runtime: provided.al2
```

`Cargo.toml` 檔案：

```
[package]
name = "test-handler"
version = "0.1.0"
edition = "2021"

[dependencies]
lambda_runtime = "0.6.0"
serde = "1.0.136"
tokio = { version = "1", features = ["macros"] }
tracing = { version = "0.1", features = ["log"] }
tracing-subscriber = { version = "0.3", default-features = false, features = ["fmt"] }

[[bin]]
name = "function_a"
path = "src/function_a.rs"

[[bin]]
name = "function_b"
path = "src/function_b.rs"
```

# 在 uv中使用 建置 Python Lambda 函數 AWS SAM
<a name="building-python-uv"></a>


|  | 
| --- |
| 此功能目前為 的預覽版本 AWS SAM ，可能會有所變更。 | 

使用 AWS Serverless Application Model 命令列界面 (AWS SAM CLI) 搭配 uv，這是一個快速的 Python 套件安裝程式和解析程式，來建置您的 Python AWS Lambda 函數。

**Topics**
+ [先決條件](#building-python-uv-prerequisites)
+ [設定 AWS SAM 搭配 Python Lambda 函數和 使用 uv](#building-python-uv-configure)
+ [範例](#building-python-uv-examples)

## 先決條件
<a name="building-python-uv-prerequisites"></a>

**Python**  
若要安裝 Python，請參閱 [Python 網站上的下載](https://www.python.org/downloads/) *Python*。

**uv**  
需要安裝 [https://docs.astral.sh/uv/](https://docs.astral.sh/uv/)，這是非常快速的 Python AWS SAM CLI套件安裝程式和解析程式。如需安裝說明，請參閱 *uv 文件*中的[安裝](https://docs.astral.sh/uv/getting-started/installation/)。

**選擇加入 AWS SAM CLI Beta 版功能**  
由於此功能處於預覽狀態，您必須使用下列其中一種方法選擇加入：  

1. 使用環境變數：`SAM_CLI_BETA_PYTHON_UV=1`。

1. 將以下內容新增到您的 `samconfig.toml` 檔案：

   ```
   [default.build.parameters]
   beta_features = true
   [default.sync.parameters]
   beta_features = true
   ```

1. 使用支援的 AWS SAM CLI命令時，請使用 `--beta-features`選項。例如：

   ```
   $ sam build --beta-features
   ```

1. 當 提示您選擇加入`y`時 AWS SAM CLI，請選擇選項。以下是範例：

   ```
   $ sam build
   Starting Build use cache
   Build method "python-uv" is a beta feature.
   Please confirm if you would like to proceed
   You can also enable this beta feature with "sam build --beta-features". [y/N]: y
   ```

## 設定 AWS SAM 搭配 Python Lambda 函數和 使用 uv
<a name="building-python-uv-configure"></a>

### 步驟 1：設定您的 AWS SAM 範本
<a name="building-python-uv-configure-template"></a>

使用下列項目設定您的 AWS SAM 範本：
+ **BuildMethod** – `python-uv`。
+ **CodeUri** – 函數程式碼目錄的路徑，其中包含 `pyproject.toml`或 `requirements.txt`。
+ **處理常**式 – 您的函數處理常式 （例如 `app.lambda_handler`)。
+ **執行時間** – Python 執行時間版本 （例如 `python3.12`)。

以下是已設定 AWS SAM 範本的範例：

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
...
Resources:
  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: ./my_function
      Handler: app.lambda_handler
      Runtime: python3.12
    Metadata:
      BuildMethod: python-uv
...
```

## 範例
<a name="building-python-uv-examples"></a>

### Hello World 範例
<a name="building-python-uv-examples-hello"></a>

**在此範例中，我們使用 Python 搭配 uv做為套件管理員，建置範例 Hello World 應用程式。**

uv 可以使用 `pyproject.toml`或 `requirements.txt`讀取相依性。如果同時提供兩者， `sam build`將從 `requirements.txt` 讀取相依性。

以下是 Hello World 應用程式的結構：

```
hello-python-uv
├── README.md
├── events
│   └── event.json
├── hello_world
│   ├── __init__.py
│   ├── app.py
│   └── pyproject.toml
├── samconfig.toml
└── template.yaml
```

`pyproject.toml` 檔案：

```
[project]
name = "my-function"
version = "0.1.0"
requires-python = ">=3.12"
dependencies = [
    "requests>=2.31.0",
    "boto3>=1.28.0",
]
```

在我們的 AWS SAM 範本中，我們的 Python 函數定義如下：

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
...
Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: hello_world/
      Handler: app.lambda_handler
      Runtime: python3.12
      Architectures:
        - x86_64
    Metadata:
      BuildMethod: python-uv
```

接下來，我們會執行 `sam build`來建置應用程式並準備部署。 AWS SAM CLI 會建立`.aws-sam`目錄，並在其中組織我們的建置成品。我們的函數相依性是使用 安裝uv，並存放在 `.aws-sam/build/HelloWorldFunction/`。

```
hello-python-uv$ sam build
Starting Build use cache
Build method "python-uv" is a beta feature.
Please confirm if you would like to proceed
You can also enable this beta feature with "sam build --beta-features". [y/N]: y

Experimental features are enabled for this session.
Visit the docs page to learn more about the AWS Beta terms https://aws.amazon.com/service-terms/.

Cache is invalid, running build and copying resources for following functions (HelloWorldFunction)
Building codeuri: /Users/.../hello-python-uv/hello_world runtime: python3.12 metadata: {'BuildMethod': 'python-uv'} architecture: x86_64 functions: HelloWorldFunction
Running PythonUvBuilder:UvBuild
Running PythonUvBuilder:CopySource

Build Succeeded

Built Artifacts  : .aws-sam/build
Built Template   : .aws-sam/build/template.yaml

Commands you can use next
=========================
[*] Validate SAM template: sam validate
[*] Invoke Function: sam local invoke
[*] Test Function in the Cloud: sam sync --stack-name {{stack-name}} --watch
[*] Deploy: sam deploy --guided
```

**注意**  
`python-uv` 建置方法會依 `Metadata`區段中的函數設定。範本中的每個函數都可以使用不同的建置方法，可讓您在相同 AWS SAM 範本中混合 uv型函數與 `pip`型函數。如果未指定建置方法，預設`pip`會使用 。

# 在 中使用自訂執行期建置 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
```

# 在 中建置 Lambda 層 AWS SAM
<a name="building-layers"></a>



您可以使用 AWS SAM 來建置自訂 Lambda 層。Lambda 層可讓您從 Lambda 函數擷取程式碼，然後可在多個 Lambda 函數之間重複使用。僅建置 Lambda 層 （而不是建置整個應用程式） 可以透過幾種方式使您受益。它可協助您減少部署套件的大小、將核心函數邏輯與相依性分開，並允許您在多個函數之間共用相依性。如需層的相關資訊，請參閱《 *AWS Lambda 開發人員指南*》中的 [AWS Lambda 層](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html)。

## 如何在 中建置 Lambda 層 AWS SAM
<a name="w2aac18c23c19c34b7"></a>

**注意**  
您必須先在 AWS SAM 範本中寫入 Lambda 層，才能建置 Lambda 層。如需執行此操作的相關資訊和範例，請參閱 [透過 使用 Lambda 層提高效率 AWS SAM](serverless-sam-cli-layers.md)。

若要建置自訂 layer，請在您的 AWS Serverless Application Model (AWS SAM) 範本檔案中宣告它，並在`BuildMethod`項目中包含`Metadata`資源屬性區段。的有效值`BuildMethod`是[AWS Lambda 執行時間](https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html)的識別符，或 `makefile`。包含`BuildArchitecture`項目以指定 layer 支援的指令集架構。的有效值`BuildArchitecture`為 [Lambda 指令集架構](https://docs.aws.amazon.com/lambda/latest/dg/foundation-arch.html)。

如果您指定 `makefile`，請提供自訂 makefile，您可以在其中宣告`build-layer-logical-id`包含 layer 建置命令之表單的建置目標。如有必要，您的 makefile 負責編譯 layer，並將建置成品複製到工作流程中後續步驟所需的適當位置。makefile 的位置是由 layer 資源的 `ContentUri` 屬性指定，且必須命名為 `Makefile`。

**注意**  
當您建立自訂 layer 時， AWS Lambda 取決於環境變數來尋找您的 layer 程式碼。Lambda 執行時間包含 layer 程式碼複製到其中的`/opt`目錄中的路徑。專案的建置成品資料夾結構必須符合執行時間的預期資料夾結構，才能找到您的自訂層程式碼。  
例如，對於 Python，您可以將程式碼放在 `python/`子目錄中。對於 NodeJS，您可以將程式碼放在 `nodejs/node_modules/`子目錄中。  
如需詳細資訊，請參閱《 *AWS Lambda 開發人員指南*》中的在 [layer 中包含程式庫相依性](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html#configuration-layers-path)。

以下是範例`Metadata`資源屬性區段。

```
    Metadata:
      BuildMethod: python3.12
      BuildArchitecture: arm64
```

**注意**  
如果您未包含`Metadata`資源屬性區段， AWS SAM 則不會建置 layer。反之，它會從 layer 資源的 `CodeUri` 屬性中指定的位置複製建置成品。如需詳細資訊，請參閱 `AWS::Serverless::LayerVersion` 資源類型的 [ContentUri](sam-resource-layerversion.md#sam-layerversion-contenturi) 屬性。

當您包含`Metadata`資源屬性區段時，您可以使用 `sam build`命令來建置 layer，無論是做為獨立物件，或是做為 AWS Lambda 函數的相依性。
+ ****做為獨立物件。****您可能只想建置 layer 物件，例如，當您在本機測試對 layer 的程式碼變更，而且不需要建置整個應用程式時。若要獨立建置 layer，請使用 `sam build layer-logical-id`命令指定 layer 資源。
+ **做為 Lambda 函數的相依性。**當您在相同 AWS SAM 範本檔案中 Lambda 函數的 `Layers` 屬性中包含 layer 的邏輯 ID 時， layer 是該 Lambda 函數的相依性。當該 layer 也包含具有`BuildMethod`項目`Metadata`的資源屬性區段時，您可以透過使用 `sam build`命令建置整個應用程式或使用 `sam build function-logical-id`命令指定函數資源來建置 layer。

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

### 範本範例 1：根據 Python 3.12 執行時間環境建置 layer
<a name="building-applications-examples-python"></a>

下列範例 AWS SAM 範本會根據 Python 3.12 執行時間環境建置 layer。

```
Resources:
  MyLayer:
    Type: AWS::Serverless::LayerVersion
    Properties:
      ContentUri: my_layer
      CompatibleRuntimes:
        - python3.12
    Metadata:
      BuildMethod: python3.12   # Required to have AWS SAM build this layer
```

### 範本範例 2：使用自訂 makefile 建置 layer
<a name="building-applications-examples-makefile"></a>

下列範例 AWS SAM 範本使用自訂 `makefile` 來建置 layer。

```
Resources:
  MyLayer:
    Type: AWS::Serverless::LayerVersion
    Properties:
      ContentUri: my_layer
      CompatibleRuntimes:
        - python3.12
    Metadata:
      BuildMethod: makefile
```

以下`makefile`包含要執行的建置目標和命令。請注意， `ContentUri` 屬性設定為 `my_layer`，因此 makefile 必須位於 `my_layer` 子目錄的根目錄，且檔案名稱必須為 `Makefile`。另請注意，建置成品會複製到 `python/`子目錄，以便 AWS Lambda 能夠找到 layer 程式碼。

```
build-MyLayer:
  mkdir -p "$(ARTIFACTS_DIR)/python"
  cp *.py "$(ARTIFACTS_DIR)/python"
  python -m pip install -r requirements.txt -t "$(ARTIFACTS_DIR)/python"
```

**注意**  
呼叫 `makefile` 時，會觸發適當的目標，並將成品複製到公開的環境變數 `$ARTIFACTS_DIR`。如需詳細資訊，請參閱 [ GitHub 中的 aws-lambda-builders](https://github.com/aws/aws-lambda-builders/blob/develop/aws_lambda_builders/workflows/custom_make/DESIGN.md)。

### 範例 sam 建置命令
<a name="building-applications-examples-commands"></a>

下列`sam build`命令會建置包含`Metadata`資源屬性區段的層。

```
# Build the 'layer-logical-id' resource independently
$ sam build layer-logical-id
            
# Build the 'function-logical-id' resource and layers that this function depends on
$ sam build function-logical-id

# Build the entire application, including the layers that any function depends on
$ sam build
```