

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

# 使用 自訂組建 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
```