

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

# 建立 Lambda 耐用函數
<a name="durable-getting-started"></a>

若要開始使用 Lambda 耐用函數，請使用 Lambda 主控台建立耐用函數。在幾分鐘內，您可以建立和部署耐久的 函數，該函數使用步驟 並等待示範檢查點型執行。

執行教學課程時，您將學習基本的耐用函數概念，例如如何使用 `DurableContext` 物件、使用步驟建立檢查點，以及使用等待暫停執行。您也將了解當您的函數在等待後恢復時，重播的運作方式。

為了保持簡單，本教學課程說明如何使用 Python 或 Node.js 執行時間來建立函數。您可以使用這些轉譯語言，直接在主控台的內建程式碼編輯器中編輯函數程式碼。

Java （預覽版） 中的耐用函數目前只能透過容器映像部署。如需從容器映像建立持久性函數的詳細資訊，請參閱[持久性函數支援的執行時間](durable-supported-runtimes.md)，或使用[基礎設施即程式碼部署 Lambda 持久性函數](durable-getting-started-iac.md)。

**注意**  
耐用函數目前支援 Python 和 Node.js (JavaScript/TypeScript) 執行期和容器映像 (OCI)，例如 Java。如需支援執行時間版本和容器映像選項的完整清單，請參閱[耐用函數支援的執行時間](durable-supported-runtimes.md)。如需搭配 Lambda 使用容器映像的詳細資訊，請參閱[《Lambda 開發人員指南》中的建立 Lambda 容器映像](https://docs.aws.amazon.com/lambda/latest/dg/images-create.html)。

**提示**  
若要了解如何建置**無伺服器解決方案**，請參閱[無伺服器開發人員指南](https://docs.aws.amazon.com/serverless/latest/devguide/)。

## 先決條件
<a name="durable-getting-started-prerequisites"></a>

### 註冊 AWS 帳戶
<a name="sign-up-for-aws"></a>

如果您沒有 AWS 帳戶，請完成下列步驟來建立一個。

**註冊 AWS 帳戶**

1. 開啟 [https://portal.aws.amazon.com/billing/signup](https://portal.aws.amazon.com/billing/signup)。

1. 請遵循線上指示進行。

   部分註冊程序需接收來電或簡訊，並在電話鍵盤輸入驗證碼。

   當您註冊 時 AWS 帳戶，*AWS 帳戶根使用者*會建立 。根使用者有權存取該帳戶中的所有 AWS 服務 和資源。作為安全最佳實務，請將管理存取權指派給使用者，並且僅使用根使用者來執行[需要根使用者存取權的任務](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html#root-user-tasks)。

AWS 會在註冊程序完成後傳送確認電子郵件給您。您可以隨時登錄 [https://aws.amazon.com/](https://aws.amazon.com/) 並選擇**我的帳戶**，以檢視您目前的帳戶活動並管理帳戶。

### 建立具有管理存取權的使用者
<a name="create-an-admin"></a>

註冊 後 AWS 帳戶，請保護 AWS 帳戶根使用者、啟用 AWS IAM Identity Center和建立管理使用者，以免將根使用者用於日常任務。

**保護您的 AWS 帳戶根使用者**

1.  選擇**根使用者**並輸入 AWS 帳戶 您的電子郵件地址，以帳戶擁有者[AWS 管理主控台](https://console.aws.amazon.com/)身分登入 。在下一頁中，輸入您的密碼。

   如需使用根使用者登入的說明，請參閱 *AWS 登入 使用者指南*中的[以根使用者身分登入](https://docs.aws.amazon.com/signin/latest/userguide/console-sign-in-tutorials.html#introduction-to-root-user-sign-in-tutorial)。

1. 若要在您的根使用者帳戶上啟用多重要素驗證 (MFA)。

   如需說明，請參閱《*IAM 使用者指南*》中的[為您的 AWS 帳戶 根使用者 （主控台） 啟用虛擬 MFA 裝置](https://docs.aws.amazon.com/IAM/latest/UserGuide/enable-virt-mfa-for-root.html)。

**建立具有管理存取權的使用者**

1. 啟用 IAM Identity Center。

   如需指示，請參閱《AWS IAM Identity Center 使用者指南》**中的[啟用 AWS IAM Identity Center](https://docs.aws.amazon.com//singlesignon/latest/userguide/get-set-up-for-idc.html)。

1. 在 IAM Identity Center 中，將管理存取權授予使用者。

   如需使用 IAM Identity Center 目錄 做為身分來源的教學課程，請參閱*AWS IAM Identity Center 《 使用者指南*》中的[使用預設值設定使用者存取 IAM Identity Center 目錄](https://docs.aws.amazon.com//singlesignon/latest/userguide/quick-start-default-idc.html)。

**以具有管理存取權的使用者身分登入**
+ 若要使用您的 IAM Identity Center 使用者簽署，請使用建立 IAM Identity Center 使用者時傳送至您電子郵件地址的簽署 URL。

  如需使用 IAM Identity Center 使用者登入的說明，請參閱*AWS 登入 《 使用者指南*》中的[登入 AWS 存取入口網站](https://docs.aws.amazon.com/signin/latest/userguide/iam-id-center-sign-in-tutorial.html)。

**指派存取權給其他使用者**

1. 在 IAM Identity Center 中，建立一個許可集來遵循套用最低權限的最佳實務。

   如需指示，請參閱《AWS IAM Identity Center 使用者指南》**中的[建立許可集](https://docs.aws.amazon.com//singlesignon/latest/userguide/get-started-create-a-permission-set.html)。

1. 將使用者指派至群組，然後對該群組指派單一登入存取權。

   如需指示，請參閱《AWS IAM Identity Center 使用者指南》**中的[新增群組](https://docs.aws.amazon.com//singlesignon/latest/userguide/addgroups.html)。

## 使用主控台建立 Lambda 耐用函數
<a name="getting-started-create-durable-function"></a>

在此範例中，您的耐用函數會使用自動檢查點處理多個步驟的訂單。函數會取得包含訂單 ID 的 JSON 物件、驗證訂單、處理付款，以及確認訂單。每個步驟都會自動檢查點，因此如果函數中斷，則會從上次完成的步驟繼續執行。

您的函數也會示範等待操作，暫停執行一小段時間以模擬等待外部確認。

**使用主控台建立耐用的函數**

1. 開啟 Lambda 主控台中的 [函數頁面](https://console.aws.amazon.com/lambda/home#/functions)。

1. 選擇**建立函數**。

1. 選取**從頭開始撰寫**。

1. 在**基本資訊**窗格中，為**函數名稱**輸入 `myDurableFunction`。

1. 針對**執行期**，選擇 **Node.js 24** 或 **Python 3.14。**

1. 選取**啟用持久性執行**。

Lambda 會使用包含檢查點操作 (`lambda:CheckpointDurableExecutions` 和 ) 許可的[執行角色](lambda-intro-execution-role.md)來建立您的耐用函數`lambda:GetDurableExecutionState`。

**注意**  
Lambda 執行時間包含持久性執行 SDK，因此您可以測試持久性函數，而無需封裝相依性。不過，我們建議您在部署套件中包含 開發套件以供生產使用。這可確保版本一致性，並避免可能影響函數的潛在執行時間更新。

使用主控台的內建程式碼編輯器來新增您的耐用函數程式碼。

------
#### [ Node.js ]

**若要在主控台中修改程式碼**

1. 選擇 **程式碼** 標籤。

   在主控台的內建程式碼編輯器中，您應該會看到 Lambda 建立的函數程式碼。如果您在程式碼編輯器中沒看到 **index.mjs** 標籤，請在檔案總管中選取 **index.mjs**，如下圖所示。  
![\[\]](http://docs.aws.amazon.com/zh_tw/lambda/latest/dg/images/durable-nodejs.png)

1. 將以下程式碼貼到 **index.mjs** 標籤中，替換 Lambda 建立的程式碼。

   ```
   import {
     DurableContext,
     withDurableExecution,
   } from "@aws/durable-execution-sdk-js";
   
   export const handler = withDurableExecution(
     async (event, context) => {
       const orderId = event.orderId;
       
       // Step 1: Validate order
       const validationResult = await context.step(async (stepContext) => {
         stepContext.logger.info(`Validating order ${orderId}`);
         return { orderId, status: "validated" };
       });
       
       // Step 2: Process payment
       const paymentResult = await context.step(async (stepContext) => {
         stepContext.logger.info(`Processing payment for order ${orderId}`);
         return { orderId, status: "paid", amount: 99.99 };
       });
       
       // Wait for 10 seconds to simulate external confirmation
       await context.wait({ seconds: 10 });
       
       // Step 3: Confirm order
       const confirmationResult = await context.step(async (stepContext) => {
         stepContext.logger.info(`Confirming order ${orderId}`);
         return { orderId, status: "confirmed" };
       });
           
       return {
         orderId: orderId,
         status: "completed",
         steps: [validationResult, paymentResult, confirmationResult]
       };
     }
   );
   ```

1. 在 **DEPLOY** 區段中，選擇**部署**以更新函數的程式碼：  
![\[\]](http://docs.aws.amazon.com/zh_tw/lambda/latest/dg/images/getting-started-tutorial/deploy-console.png)

**了解您的耐用函數程式碼**  
在進行下一個步驟之前，讓我們先查看函數程式碼，並了解關鍵的耐久函數概念。
+ `withDurableExecution` 包裝函式：

  您的耐用函數會包裝在 中`withDurableExecution`。此包裝函式提供 `DurableContext` 物件和管理檢查點操作，以啟用持久的執行。
+ `DurableContext` 物件：

  您的函數會收到 ，而不是標準 Lambda 內容`DurableContext`。此物件提供建立檢查點等耐久操作的方法`wait()`，例如 `step()`和 。
+ 步驟和檢查點：

  每個`context.step()`呼叫都會在執行前後建立檢查點。如果您的函數中斷，則會從上次完成的檢查點繼續執行。函數不會重新執行完成的步驟。它會改用其儲存的結果。
+ 等待操作：

  `context.wait()` 呼叫會暫停執行，而不會耗用運算資源。當等待完成時，Lambda 會再次叫用您的函數，並重播檢查點日誌，以儲存的值取代已完成的步驟。
+ 重播機制：

  當您的函數在等待或中斷後繼續時，Lambda 會從頭開始執行您的程式碼。不過，已完成的步驟不會重新執行。Lambda 會從檢查點日誌重播其結果。這就是您的程式碼必須具有決定性的原因。

------
#### [ Python ]

**若要在主控台中修改程式碼**

1. 選擇 **程式碼** 標籤。

   在主控台的內建程式碼編輯器中，您應該會看到 Lambda 建立的函數程式碼。如果您在程式碼編輯器中沒看到 **lambda\$1function.py**，請在檔案總管中選取 **lambda\$1function.py**，如下圖所示。  
![\[\]](http://docs.aws.amazon.com/zh_tw/lambda/latest/dg/images/durable-python.png)

1. 將以下程式碼貼到 **lambda\$1function.py** 標籤中，替換 Lambda 建立的程式碼。

   ```
   from aws_durable_execution_sdk_python import (
       DurableContext,
       durable_execution,
       durable_step,
   )
   from aws_durable_execution_sdk_python.config import Duration
   
   @durable_step
   def validate_order(step_context, order_id):
       step_context.logger.info(f"Validating order {order_id}")
       return {"orderId": order_id, "status": "validated"}
   
   @durable_step
   def process_payment(step_context, order_id):
       step_context.logger.info(f"Processing payment for order {order_id}")
       return {"orderId": order_id, "status": "paid", "amount": 99.99}
   
   @durable_step
   def confirm_order(step_context, order_id):
       step_context.logger.info(f"Confirming order {order_id}")
       return {"orderId": order_id, "status": "confirmed"}
   
   @durable_execution
   def lambda_handler(event, context: DurableContext):
       order_id = event['orderId']
       
       # Step 1: Validate order
       validation_result = context.step(validate_order(order_id))
       
       # Step 2: Process payment
       payment_result = context.step(process_payment(order_id))
       
       # Wait for 10 seconds to simulate external confirmation
       context.wait(Duration.from_seconds(10))
       
       # Step 3: Confirm order
       confirmation_result = context.step(confirm_order(order_id))
           
       return {
           "orderId": order_id,
           "status": "completed",
           "steps": [validation_result, payment_result, confirmation_result]
       }
   ```

1. 在 **DEPLOY** 區段中，選擇**部署**以更新函數的程式碼：  
![\[\]](http://docs.aws.amazon.com/zh_tw/lambda/latest/dg/images/getting-started-tutorial/deploy-console.png)

**了解您的耐用函數程式碼**  
在進行下一個步驟之前，讓我們先查看函數程式碼，並了解關鍵的耐久函數概念。
+ `@durable_execution` 裝飾項目：

  您的處理常式函數以 裝飾`@durable_execution`。此裝飾項目透過提供 `DurableContext` 物件和管理檢查點操作來實現持久的執行。
+ `@durable_step` 裝飾項目：

  每個步驟函數都以 裝飾`@durable_step`。此裝飾項目會將函數標記為建立檢查點的耐久步驟。
+ `DurableContext` 物件：

  您的函數會收到 ，而不是標準 Lambda 內容`DurableContext`。此物件提供建立檢查點等耐久操作的方法`wait()`，例如 `step()`和 。
+ 步驟和檢查點：

  每個`context.step()`呼叫都會在執行前後建立檢查點。如果您的函數中斷，則會從上次完成的檢查點繼續執行。函數不會重新執行完成的步驟。它會改用其儲存的結果。
+ 等待操作：

  `context.wait()` 呼叫會暫停執行，而不會耗用運算資源。當等待完成時，Lambda 會再次叫用您的函數，並重播檢查點日誌，以儲存的值取代已完成的步驟。
+ Python SDK 是同步的：

  請注意，Python SDK 不使用 `await`。所有耐用的操作都是同步方法呼叫。

------

## 使用主控台程式碼編輯器叫用耐用函數
<a name="get-started-invoke-durable-manually"></a>

未指定明確版本 （或發佈） 時，主控台會使用`$LATEST`版本限定詞叫用耐久函數。不過，為了決定性執行程式碼，您必須一律使用指向穩定版本的合格 ARN。

**發佈函數的版本**

1. 選擇**版本**索引標籤。

1. 選擇 **Publish new version (發佈新版本)**。

1. 針對**版本描述**，輸入 **Initial version**（選用）。

1. 選擇**發布**。

1. Lambda 會建立函數的第 1 版。請注意，函數 ARN 現在`:1`會在結尾包含 ，表示這是第 1 版。

現在建立測試事件以傳送至您的 函數。事件是包含訂單 ID 的 JSON 格式文件。

**若要建立測試事件**

1. 在主控台程式碼編輯器的 **TEST EVENTS** 區段中，選擇**建立測試事件**。  
![\[\]](http://docs.aws.amazon.com/zh_tw/lambda/latest/dg/images/getting-started-tutorial/test-event.png)

1. **Event Name (事件名稱)** 輸入 **myTestEvent**。

1. 在**事件 JSON** 區段中，將預設 JSON 取代為下列項目：

   ```
   {
     "orderId": "order-12345"
   }
   ```

1. 選擇**儲存**。

**測試您的耐用函數並檢視執行**

在主控台程式碼編輯器的 **TEST EVENTS** 區段中，選擇測試事件旁邊的執行圖示：

![\[\]](http://docs.aws.amazon.com/zh_tw/lambda/latest/dg/images/getting-started-tutorial/run-test-event.png)


您的耐用函數會開始執行。因為它包含 10 秒的等待時間，初始調用會快速完成，而且函數會在等待期間之後繼續。您可以在**持久性執行索引標籤中檢視執行**進度。

**檢視您的耐久函數執行**

1. 選擇**持久性執行**索引標籤。

1. 在清單中尋找您的執行。執行會顯示目前狀態 （執行中、成功或失敗）。

1. 選擇執行 ID 以檢視詳細資訊，包括：
   + 顯示每個步驟完成時間的執行時間表
   + 檢查點歷史記錄
   + 等待期間
   + 步驟結果

您也可以在 CloudWatch Logs 中檢視函數的日誌，以查看每個步驟的主控台輸出。

**若要在 CloudWatch Logs 中檢視函數的調用記錄**

1. 開啟 CloudWatch 主控台的 [日誌群組](https://console.aws.amazon.com/cloudwatch/home#logs:) 頁面。

1. 為函數 (`/aws/lambda/myDurableFunction`) 選擇日誌群組名稱。

1. 向下捲動並選擇要查看的函數調用**日誌串流**。  
![\[\]](http://docs.aws.amazon.com/zh_tw/lambda/latest/dg/images/log-stream.png)

   您應該會看到每次叫用函數的日誌項目，包括初始執行和等待後的重播。

**注意**  
當您從 `DurableContext`（例如 `context.logger`或 `stepContext.logger`) 使用記錄器時，日誌也會出現在 Lambda 主控台的耐久執行和步驟檢視中。這些日誌可能需要一些時間才能載入。

## 清除
<a name="gettingstarted-durable-cleanup"></a>

當您完成使用範例耐用函數時，請將其刪除。您還可以刪除存放函數日誌的日誌群組，以及主控台建立的[執行角色](lambda-intro-execution-role.md)。

**若要刪除 Lambda 函數**

1. 開啟 Lambda 主控台中的 [函數頁面](https://console.aws.amazon.com/lambda/home#/functions)。

1. 選擇您建立的函數。

1. 選擇 **Actions** (動作)、**Delete** (刪除)。

1. 在文字輸入欄位中輸入 **confirm**，然後選擇**刪除**。

**刪除日誌群組**

1. 開啟 CloudWatch 主控台的 [日誌群組](https://console.aws.amazon.com/cloudwatch/home#logs:) 頁面。

1. 選取函數的日誌群組 (`/aws/lambda/myDurableFunction`)。

1. 選擇 **動作** 、**刪除日誌群組** 。

1. 在 **刪除日誌群組** 對話方塊中，選擇 **刪除** 。

**刪除執行角色**

1. 開啟 AWS Identity and Access Management (IAM) 主控台的角色[頁面](https://console.aws.amazon.com/iam/home?#/roles)。

1. 選取函數的執行角色，(例如 `myDurableFunction-role-31exxmpl`)。

1. 選擇 **刪除**。

1. 在**刪除角色**對話方塊中輸入角色名稱，然後選擇**刪除**。

## 其他資源和後續步驟
<a name="durable-getting-started-more-resources"></a>

現在您已使用 主控台建立並測試簡單的耐用函數，請採取下列後續步驟：
+ 了解耐用函數的常見使用案例，包括分散式交易、訂單處理和人工審核工作流程。請參閱[範例](durable-examples.md)。
+ 了解如何使用 CloudWatch 指標和執行歷史記錄監控持久的函數執行。請參閱[監控和偵錯](durable-monitoring.md)。
+ 了解如何同步和非同步叫用耐久函數，以及管理長時間執行的執行。請參閱[叫用耐用函數](durable-invoking.md)。
+ 遵循撰寫確定性程式碼、管理檢查點大小和最佳化成本的最佳實務。請參閱[最佳實務](durable-best-practices.md)。
+ 了解如何在本機和雲端測試耐用的函數。請參閱[測試耐用函數](durable-testing.md)。
+ 比較耐用的函數與 Step Functions，以了解每個方法最有效的時機。請參閱[耐用函數或 Step Functions](durable-step-functions.md)。

# 使用 部署和叫用 Lambda 耐用函數 AWS CLI
<a name="durable-getting-started-cli"></a>

使用 AWS CLI 以使用命令建立和部署 Lambda 耐用函數。此方法可讓您直接控制部署程序的每個步驟。

## 先決條件
<a name="durable-cli-prerequisites"></a>
+ 安裝及設定 AWS CLI。如需說明，請參閱[安裝 AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)。
+ 使用函數程式碼和耐用的執行 SDK 建立部署套件。
+ 建立具有檢查點許可的 IAM 執行角色。

## 建立執行角色
<a name="durable-cli-create-role"></a>

建立具有基本 Lambda 執行和檢查點操作許可的 IAM 角色。

**建立執行角色**

1. 建立允許 Lambda 擔任角色的信任政策文件。將此儲存為 `trust-policy.json`：

   ```
   {
     "Version": "2012-10-17",		 	 	 
     "Statement": [
       {
         "Effect": "Allow",
         "Principal": {
           "Service": "lambda.amazonaws.com"
         },
         "Action": "sts:AssumeRole"
       }
     ]
   }
   ```

1. 建立角色：

   ```
   aws iam create-role \
     --role-name durable-function-role \
     --assume-role-policy-document file://trust-policy.json
   ```

1. 連接檢查點操作和基本執行的耐久執行政策：

   ```
   aws iam attach-role-policy \
     --role-name durable-function-role \
     --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicDurableExecutionRolePolicy
   ```

`AWSLambdaBasicDurableExecutionRolePolicy` 受管政策包含檢查點操作 (`lambda:CheckpointDurableExecutions` 和 `lambda:GetDurableExecutionState`) 和基本 Lambda 執行所需的許可。

## 建立耐用的 函數
<a name="durable-cli-create-function"></a>

使用 `--durable-config` 參數建立您的耐用函數。

**建立耐用的函數**

1. 將具有相依性的函數程式碼封裝至 .zip 檔案：

   ```
   zip -r function.zip index.mjs node_modules/
   ```

1. 建立已啟用持久性執行的函數：

   ```
   aws lambda create-function \
     --function-name myDurableFunction \
     --runtime nodejs22.x \
     --role arn:aws:iam::123456789012:role/durable-function-role \
     --handler index.handler \
     --zip-file fileb://function.zip \
     --durable-config '{"ExecutionTimeout": 3600, "RetentionPeriodInDays": 7}'
   ```

**注意**  
您只能在建立函數時啟用持久性執行。您無法在現有函數上啟用它。

**注意**  
目前 Java （預覽） 中的耐用函數只能透過容器映像建立。如需從容器映像建立持久性函數的詳細資訊，請參閱[持久性函數支援的執行時間](durable-supported-runtimes.md)。

## 發佈版本
<a name="durable-cli-publish-version"></a>

雖然可以使用`$LATEST`版本限定詞叫用耐久的函數，但您必須一律使用指向穩定版本的合格 ARN，以確保程式碼的確定性執行。

```
aws lambda publish-version \
  --function-name myDurableFunction \
  --description "Initial version"
```

命令會傳回版本 ARN。請注意 ARN 結尾的版本編號 （例如 `:1`)。

或者，建立指向 版本的別名：

```
aws lambda create-alias \
  --function-name myDurableFunction \
  --name prod \
  --function-version 1
```

## 叫用耐用的 函數
<a name="durable-cli-invoke"></a>

使用合格的 ARN （版本或別名） 叫用您的耐久函數。

**注意**  
**等冪叫用：**若要防止重試失敗叫用時重複執行，您可以提供執行名稱，確保at-most-once。如需詳細資訊，請參閱[等冪性](durable-execution-idempotency.md)。

**同步調用**  
對於在 15 分鐘內完成的執行，請使用同步調用：

```
aws lambda invoke \
  --function-name myDurableFunction:1 \
  --payload '{"orderId": "order-12345"}' \
  --cli-binary-format raw-in-base64-out \
  response.json
```

或使用別名：

```
aws lambda invoke \
  --function-name myDurableFunction:prod \
  --payload '{"orderId": "order-12345"}' \
  --cli-binary-format raw-in-base64-out \
  response.json
```

**非同步調用**  
對於長時間執行的執行，請使用非同步調用：

```
aws lambda invoke \
  --function-name myDurableFunction:prod \
  --invocation-type Event \
  --payload '{"orderId": "order-12345"}' \
  --cli-binary-format raw-in-base64-out \
  response.json
```

使用非同步調用時，Lambda 會立即傳回 。函數會繼續在背景執行。

**注意**  
您可以在 主控台中使用 `$LATEST`進行原型設計和測試。對於生產工作負載，請使用發佈的版本或別名。

## 管理持久的執行
<a name="durable-cli-manage-executions"></a>

使用下列命令來管理和監控耐用的函數執行。

**列出執行**  
列出耐用函數的所有執行：

```
aws lambda list-durable-executions-by-function \
  --function-name myDurableFunction
```

**取得執行詳細資訊**  
取得特定執行的詳細資訊：

```
aws lambda get-durable-execution \
  --durable-execution-arn arn:aws:lambda:us-east-1:123456789012:function:myDurableFunction:my-function-version/durable-execution/my-execution-name/my-execution-id
```

**取得執行歷史記錄**  
檢視執行的檢查點歷史記錄：

```
aws lambda get-durable-execution-history \
  --durable-execution-arn arn:aws:lambda:us-east-1:123456789012:function:myDurableFunction:my-function-version/durable-execution/my-execution-name/my-execution-id
```

**停止執行**  
停止執行中的耐久執行：

```
aws lambda stop-durable-execution \
  --durable-execution-arn arn:aws:lambda:us-east-1:123456789012:function:myDurableFunction:my-function-version/durable-execution/my-execution-name/my-execution-id
```

## 更新函數程式碼
<a name="durable-cli-update-function"></a>

更新您的耐用函數程式碼並發佈新版本：

**更新和發佈新版本**

1. 更新函數程式碼：

   ```
   aws lambda update-function-code \
     --function-name myDurableFunction \
     --zip-file fileb://function.zip
   ```

1. 等待更新完成：

   ```
   aws lambda wait function-updated \
     --function-name myDurableFunction
   ```

1. 發佈新版本：

   ```
   aws lambda publish-version \
     --function-name myDurableFunction \
     --description "Updated order processing logic"
   ```

1. 更新別名以指向新版本：

   ```
   aws lambda update-alias \
     --function-name myDurableFunction \
     --name prod \
     --function-version 2
   ```

**重要**  
執行中的執行會繼續使用其啟動的版本。新的調用使用更新的別名版本。

## 檢視函數日誌
<a name="durable-cli-view-logs"></a>

在 CloudWatch Logs 中檢視耐用函數的日誌：

```
aws logs tail /aws/lambda/myDurableFunction --follow
```

篩選特定執行的日誌：

```
aws logs filter-log-events \
  --log-group-name /aws/lambda/myDurableFunction \
  --filter-pattern "exec-abc123"
```

## 清除資源
<a name="durable-cli-cleanup"></a>

刪除您的耐用函數和相關聯的資源：

```
# Delete the function
aws lambda delete-function --function-name myDurableFunction

# Delete the IAM role policies
aws iam detach-role-policy \
  --role-name durable-function-role \
  --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole

aws iam detach-role-policy \
  --role-name durable-function-role \
  --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicDurableExecutionRolePolicy

# Delete the role
aws iam delete-role --role-name durable-function-role
```

## 後續步驟
<a name="durable-cli-next-steps"></a>

使用 部署您的耐用函數之後 AWS CLI：
+ 使用 `list-durable-executions`和 `get-durable-execution`命令監控執行
+ 檢視 AWS CloudTrail 資料事件中的檢查點操作
+ 針對執行失敗或長時間執行的執行設定 CloudWatch 警示
+ 使用 shell 指令碼或 CI/CD 管道自動化部署

如需 Lambda AWS CLI 命令的詳細資訊，請參閱 [AWS CLI 命令參考](https://docs.aws.amazon.com/cli/latest/reference/lambda/index.html)。

# 使用 Infrastructure as Code 部署 Lambda 耐用函數
<a name="durable-getting-started-iac"></a>

您可以使用 Infrastructure as Code (IaC) 工具部署 Lambda 耐用函數 AWS CloudFormation，例如 AWS CDK AWS Serverless Application Model， 或 Terraform。這些工具可讓您在程式碼中定義函數、執行角色和許可，讓部署可重複且受版本控制。

這三個工具都需要您：
+ 在函數上啟用持久性執行
+ 將檢查點許可授予執行角色
+ 發佈版本或建立別名 （持久性函數需要合格的 ARNs)

## ZIP 中的耐用函數
<a name="durable-iac-zip"></a>

### AWS CloudFormation
<a name="durable-iac-cloudformation"></a>

使用 在範本中 CloudFormation 定義您的耐用函數。下列範例會建立具有所需許可的耐用函數。

```
AWSTemplateFormatVersion: '2010-09-09'
Description: Lambda durable function example

Resources:
  DurableFunctionRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'		 	 	 
        Statement:
          - Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
            Action: sts:AssumeRole
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicDurableExecutionRolePolicy

  DurableFunction:
    Type: AWS::Lambda::Function
    Properties:
      FunctionName: myDurableFunction
      Runtime: nodejs22.x
      Handler: index.handler
      Role: !GetAtt DurableFunctionRole.Arn
      Code:
        ZipFile: |
          // Your durable function code here
          export const handler = async (event, context) => {
            return { statusCode: 200 };
          };
      DurableConfig:
        ExecutionTimeout: 3600
        RetentionPeriodInDays: 7

  DurableFunctionVersion:
    Type: AWS::Lambda::Version
    Properties:
      FunctionName: !Ref DurableFunction
      Description: Initial version

  DurableFunctionAlias:
    Type: AWS::Lambda::Alias
    Properties:
      FunctionName: !Ref DurableFunction
      FunctionVersion: !GetAtt DurableFunctionVersion.Version
      Name: prod

Outputs:
  FunctionArn:
    Description: Durable function ARN
    Value: !GetAtt DurableFunction.Arn
  AliasArn:
    Description: Function alias ARN (use this for invocations)
    Value: !Ref DurableFunctionAlias
```

**部署範本**

```
aws cloudformation deploy \
  --template-file template.yaml \
  --stack-name my-durable-function-stack \
  --capabilities CAPABILITY_IAM
```

### AWS CDK
<a name="durable-iac-cdk"></a>

AWS CDK 可讓您使用程式設計語言定義基礎設施。下列範例示範如何使用 TypeScript 和 Python 建立耐用的函數。

------
#### [ TypeScript ]

```
import * as cdk from 'aws-cdk-lib';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as iam from 'aws-cdk-lib/aws-iam';
import { Construct } from 'constructs';

export class DurableFunctionStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    // Create the durable function
    const durableFunction = new lambda.Function(this, 'DurableFunction', {
      runtime: lambda.Runtime.NODEJS_22_X,
      handler: 'index.handler',
      code: lambda.Code.fromAsset('lambda'),
      functionName: 'myDurableFunction',
      durableConfig: { executionTimeout: Duration.hours(1), retentionPeriod: Duration.days(30) },
    });

    // Create version and alias
    const version = durableFunction.currentVersion;
    const alias = new lambda.Alias(this, 'ProdAlias', {
      aliasName: 'prod',
      version: version,
    });

    // Output the alias ARN
    new cdk.CfnOutput(this, 'FunctionAliasArn', {
      value: alias.functionArn,
      description: 'Use this ARN to invoke the durable function',
    });
  }
}
```

------
#### [ Python ]

```
from aws_cdk import (
    Stack,
    aws_lambda as lambda_,
    aws_iam as iam,
    CfnOutput,
)
from constructs import Construct

class DurableFunctionStack(Stack):
    def __init__(self, scope: Construct, id: str, **kwargs):
        super().__init__(scope, id, **kwargs)

        # Create the durable function
        durable_function = lambda_.Function(
            self, 'DurableFunction',
            runtime=lambda_.Runtime.NODEJS_22_X,
            handler='index.handler',
            code=lambda_.Code.from_asset('lambda'),
            function_name='myDurableFunction',
            durable_execution={execution_timeout: Duration.hours(1), retention_period: Duration.days(30)}
        )

        # Add durable execution managed policy for checkpoint permissions
        durable_function.role.add_managed_policy(
            iam.ManagedPolicy.from_aws_managed_policy_name('service-role/AWSLambdaBasicDurableExecutionRolePolicy')
        )

        # Create version and alias
        version = durable_function.current_version
        alias = lambda_.Alias(
            self, 'ProdAlias',
            alias_name='prod',
            version=version
        )

        # Output the alias ARN
        CfnOutput(
            self, 'FunctionAliasArn',
            value=alias.function_arn,
            description='Use this ARN to invoke the durable function'
        )
```

------

**部署 CDK 堆疊**

```
cdk deploy
```

### AWS Serverless Application Model
<a name="durable-iac-sam"></a>

AWS SAM 簡化無伺服器應用程式的 CloudFormation 範本。下列範本使用 建立耐久的 函數 AWS SAM。

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: Lambda durable function with SAM

Resources:
  DurableFunction:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: myDurableFunction
      Runtime: nodejs22.x
      Handler: index.handler
      CodeUri: ./src
      DurableConfig:
        ExecutionTimeout: 3600
        RetentionPeriodInDays: 7
      Policies:
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicDurableExecutionRolePolicy
      AutoPublishAlias: prod

Outputs:
  FunctionArn:
    Description: Durable function ARN
    Value: !GetAtt DurableFunction.Arn
  AliasArn:
    Description: Function alias ARN (use this for invocations)
    Value: !Ref DurableFunction.Alias
```

**部署 SAM 範本**

```
sam build
sam deploy --guided
```

### Terraform
<a name="durable-iac-terraform"></a>

Terraform 是支援 AWS 資源的熱門開放原始碼 IaC 工具。下列範例使用 AWS 提供者版本 6.25.0 或更新版本，使用 Terraform 建立耐久的函數。

```
terraform {
  required_version = ">= 1.0"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = ">= 6.25.0"
    }
  }
}

provider "aws" {
  region = "us-east-2"
}

# IAM Role for Lambda Function
resource "aws_iam_role" "lambda_role" {
  name = "durable-function-role"

  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Action = "sts:AssumeRole"
      Effect = "Allow"
      Principal = {
        Service = "lambda.amazonaws.com"
      }
    }]
  })
}

# Attach durable execution policy for checkpoint operations
resource "aws_iam_role_policy_attachment" "lambda_durable" {
  policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicDurableExecutionRolePolicy"
  role       = aws_iam_role.lambda_role.name
}

# Lambda Function with Durable Execution enabled
resource "aws_lambda_function" "durable_function" {
  filename      = "function.zip"
  function_name = "myDurableFunction"
  role          = aws_iam_role.lambda_role.arn
  handler       = "index.handler"
  runtime       = "nodejs22.x"
  timeout       = 30
  memory_size   = 512

  durable_config {
    execution_timeout = 900
    retention_period  = 7
  }
}

# Publish a version
resource "aws_lambda_alias" "prod" {
  name             = "prod"
  function_name    = aws_lambda_function.durable_function.function_name
  function_version = aws_lambda_function.durable_function.version
}

output "function_arn" {
  description = "ARN of the Lambda function"
  value       = aws_lambda_function.durable_function.arn
}

output "alias_arn" {
  description = "ARN of the function alias (use this for invocations)"
  value       = aws_lambda_alias.prod.arn
}
```

**使用 Terraform 部署**

```
terraform init
terraform plan
terraform apply
```

**注意**  
Lambda 耐久函數的 Terraform 支援需要 AWS 提供者版本 6.25.0 或更新版本。如果您使用的是舊版，請更新您的提供者版本。

## 來自 OCI 容器映像的耐用函數
<a name="durable-iac-oci"></a>

您也可以根據容器映像建立耐久函數。如需如何建置容器映像的指示，請參閱[耐用函數支援的執行時間](durable-supported-runtimes.md)。

### AWS CDK
<a name="durable-iac-oci-cdk"></a>

AWS CDK 可讓您使用程式設計語言定義基礎設施。下列範例示範如何從容器映像使用 TypeScript 建立耐用的函數。

```
import * as cdk from 'aws-cdk-lib';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as iam from 'aws-cdk-lib/aws-iam';
import { Construct } from 'constructs';

export class DurableFunctionStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    // Create the durable function
    const durableFunction = new lambda.DockerImageFunction(this, 'DurableFunction', {
      code: lambda.DockerImageCode.fromImageAsset('./lambda', {
        platform: cdk.aws_ecr_assets.Platform.LINUX_AMD64,
      }),
      functionName: 'myDurableFunction',
      memorySize: 512,
      timeout: cdk.Duration.seconds(30),
      durableConfig: { executionTimeout: cdk.Duration.hours(1), retentionPeriod: cdk.Duration.days(30) },
    });

    // Create version and alias
    const version = durableFunction.currentVersion;
    const alias = new lambda.Alias(this, 'ProdAlias', {
      aliasName: 'prod',
      version: version,
    });

    // Output the alias ARN
    new cdk.CfnOutput(this, 'FunctionAliasArn', {
      value: alias.functionArn,
      description: 'Use this ARN to invoke the durable function',
    });
  }
}
```

**部署 CDK 堆疊**

```
cdk deploy
```

### AWS Serverless Application Model
<a name="durable-iac-oci-sam"></a>

AWS SAM 簡化無伺服器應用程式的 CloudFormation 範本。下列範本使用 建立耐久的 函數 AWS SAM。

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: Lambda durable function with SAM

Resources:
  DurableFunction:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: myDurableFunction
      PackageType: Image
      ImageUri: ./src
      DurableConfig:
        ExecutionTimeout: 3600
        RetentionPeriodInDays: 7
      Policies:
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicDurableExecutionRolePolicy
      AutoPublishAlias: prod
    Metadata:
      DockerTag: latest
      DockerContext: ./src
      Dockerfile: Dockerfile

Outputs:
  FunctionArn:
    Description: Durable function ARN
    Value: !GetAtt DurableFunction.Arn
  AliasArn:
    Description: Function alias ARN (use this for invocations)
    Value: !Ref DurableFunction.Alias
```

**部署 SAM 範本**

```
sam build
sam deploy --guided
```

## 常見的組態模式
<a name="durable-iac-common-patterns"></a>

無論您使用哪種 IaC 工具，請遵循這些模式以取得耐用的函數：

**啟用持久性執行**  
在函數上設定 `DurableConfig` 屬性以啟用持久性執行。此屬性僅在建立函數時可用。您無法在現有函數上啟用持久性執行。

**授予檢查點許可**  
將 `AWSLambdaBasicDurableExecutionRolePolicy`受管政策連接至執行角色。此政策包含必要的 `lambda:CheckpointDurableExecutions`和 `lambda:GetDurableExecutionState`許可。

**使用合格的 ARNs**  
為您的函數建立版本或別名。耐用的函數需要合格的 ARNs（具有版本或別名） 才能叫用。在 `AutoPublishAlias`中使用 AWS SAM 或在 CloudFormation AWS CDK和 Terraform 中建立明確版本。

**套件相依性**  
在您的部署套件中包含耐用的執行 SDK。對於 Node.js，安裝 `@aws/durable-execution-sdk-js`。針對 Python，安裝 `aws-durable-execution-sdk-python`。

## 後續步驟
<a name="durable-iac-next-steps"></a>

部署您的耐用函數之後：
+ 使用合格的 ARN （版本或別名） 測試您的函數
+ 在持久性執行索引標籤下的 Lambda 主控台中監控執行進度
+ 檢視 AWS CloudTrail 資料事件中的檢查點操作
+ 檢閱 CloudWatch Logs 以取得函數輸出和重播行為

如需使用 IaC 工具部署 Lambda 函數的詳細資訊，請參閱：
+ [CloudFormation AWS::Lambda::Function 參考](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-function.html)
+ [AWS CDK Lambda 模組文件](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda-readme.html)
+ [AWS SAM 開發人員指南](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/what-is-sam.html)