

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

# 使用 建置 簡介 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。