

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

# 使用 AWS Fargate WaitCondition 勾點建構來協調資源相依性和任務執行
<a name="use-the-aws-fargate-waitcondition-hook-construct"></a>

*Stan Fan，Amazon Web Services*

## 摘要
<a name="use-the-aws-fargate-waitcondition-hook-construct-summary"></a>

此模式描述 WaitCondition hook (`waitcondition-hook-for-aws-fargate-task`) npm 套件，這是雲端原生解決方案，專為在 Amazon Elastic Container Service (Amazon ECS) 叢集中協調[AWS Fargate](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/AWS_Fargate.html)任務而設計。

WaitCondition 掛鉤是一種專門為 整合量身打造的 AWS Cloud Development Kit (AWS CDK) 建構 AWS CloudFormation。WaitCondition 掛鉤提供下列關鍵功能：
+ 做為等待條件機制，暫停 CloudFormation 堆疊執行，直到指定的 Fargate 任務完成，這有助於有序的部署和資源佈建。
+ 支援 TypeScript 和 Python，使其非常適合 AWS CDK 專案。
+ 允許開發人員和架構師協調容器化應用程式的任務完成和資源管理，以協調部署 AWS。
+ 使用內嵌在 CloudFormation 生命週期中的一或多個容器來執行 Fargate 任務。 和 可以在任務失敗後處理任務失敗並復原 CloudFormation 堆疊。
+ 提供彈性，在資源與 Fargate 任務執行結果之間新增相依性，啟用自訂任務或叫用其他端點。例如，您可以暫停 CloudFormation 堆疊並等待資料庫遷移 （由 Fargate 任務完成），並佈建可能取決於資料庫遷移成功的其他資源。

## 先決條件和限制
<a name="use-the-aws-fargate-waitcondition-hook-construct-prereqs"></a>

**先決條件**
+ 作用中 AWS 帳戶。
+ AWS Cloud Development Kit (AWS CDK) 安裝在本機工作站上的命令列界面 (CLI)。如需詳細資訊，請參閱 AWS CDK 文件中的 [AWS CDK CLI 參考](https://docs.aws.amazon.com/cdk/v2/guide/cli.html)。
+ 節點套件管理員 (npm)，安裝在本機工作站上，並在 [AWS CDK TypeScript 中](https://docs.aws.amazon.com/cdk/v2/guide/work-with-cdk-typescript.html)為 設定。如需詳細資訊，請參閱 [npm 文件中的下載並安裝 Node.js 和](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm) npm。
+ 安裝在本機工作站上的 Yarn。如需詳細資訊，請參閱 Yarn 文件中的 [安裝](https://yarnpkg.com/getting-started/install)。

**限制**
+ 此解決方案會部署到單一 AWS 帳戶。
+ 容器的預期傳回碼`0`是為了成功。任何其他傳回碼表示失敗，CloudFormation 堆疊將復原。
+ 有些 AWS 服務 無法全部使用 AWS 區域。如需區域可用性，請參閱[AWS 服務 依區域](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/)。如需特定端點，請參閱[服務端點和配額](https://docs.aws.amazon.com/general/latest/gr/aws-service-information.html)，然後選擇服務的連結。

## Architecture
<a name="use-the-aws-fargate-waitcondition-hook-construct-architecture"></a>

下圖顯示建構架構。

![\[waitcondition-hook-for-aws-fargate-task 建構的 AWS Step Functions 工作流程。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/e58680e3-f89f-422f-b0e1-e85605ae8bf9/images/598020df-908c-4486-9844-c05af759c18a.png)


圖表顯示 的工作流程`waitcondition-hook-for-aws-fargate-task`：

1. `WaitCondition` 和 `WaitConditionHandler` 會佈建為接聽 AWS Lambda 函數的回應。

1. 根據任務的結果， `CallbackFunction`或 `ErrorHandlerFunction`是由 Fargate 任務的完成所觸發。

1. Lambda 函數會將 SUCCEED 或 FAILURE 訊號傳送至 `WaitConditionHandler`。

1. `WaitConditionHandler` 如果 Fargate 任務的執行結果成功， 會繼續佈建資源，或在任務失敗時轉返堆疊。

下圖顯示執行資料庫遷移的工作流程範例。

![\[使用 WaitCondition hook 建構的 Amazon RDS 資料庫遷移工作流程。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/e58680e3-f89f-422f-b0e1-e85605ae8bf9/images/3b83fc2a-80bb-4ba9-9637-782060493cf0.png)


範例工作流程使用 `waitcondition-hook-for-aws-fargate-task` 建構來執行資料庫遷移，如下所示：

1. 已佈建 Amazon Relational Database Service (Amazon RDS) 執行個體。

1. `waitcondition-hook-for-aws-fargate-task` 建構模組會執行資料庫遷移任務，並將堆疊暫停為 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體。

1. 如果遷移任務成功完成，它會向 CloudFormation 傳送成功訊號。否則，它會將失敗訊號傳送至 CloudFormation 並轉返堆疊。

## 工具
<a name="use-the-aws-fargate-waitcondition-hook-construct-tools"></a>

**AWS 服務**
+ [AWS Cloud Development Kit (AWS CDK)](https://docs.aws.amazon.com/cdk/v2/guide/home.html) 是一種軟體開發架構，可協助您在程式碼中定義雲端基礎設施並進行佈建 CloudFormation。
+ [CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) 可協助您設定 AWS 資源、快速且一致地佈建資源，以及在整個 AWS 帳戶 和 生命週期中管理資源 AWS 區域。
+ [Amazon CloudWatch](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/WhatIsCloudWatch.html) 可協助您 AWS 即時監控 AWS 資源的指標，以及您在 上執行的應用程式。
+ [Amazon Elastic Container Service (Amazon ECS)](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/Welcome.html) 是快速、可擴展的容器管理服務，可協助您執行、停止和管理叢集上的容器。
+ [AWS Fargate](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/AWS_Fargate.html) 可協助您執行容器，而不需要管理伺服器或 Amazon EC2 執行個體。它與 Amazon ECS 搭配使用。
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) 透過控制已驗證並獲授權使用的人員，協助您安全地管理對 AWS 資源的存取。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一項運算服務，可協助您執行程式碼，無需佈建或管理伺服器。它只會在需要時執行程式碼並自動擴展，因此您只需按使用的運算時間付費。
+ [AWS Step Functions](https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html) 是一種無伺服器協同運作服務，可協助您結合 AWS Lambda 函數和其他 AWS 服務 來建置業務關鍵型應用程式。
+ [Amazon Virtual Private Cloud (Amazon VPC)](https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html) 可協助您在已定義的虛擬網路中啟動 AWS 資源。此虛擬網路類似於傳統網路，您可以在自己的資料中心中操作，並享有使用 可擴展基礎設施的優勢 AWS。

**其他工具**
+ [npm](https://docs.npmjs.com/about-npm) 是在 Node.js 環境中執行的軟體登錄檔，用於共用或借用套件和管理私有套件的部署。
+ [Yarn](https://yarnpkg.com/) 是開放原始碼套件管理員，可用來管理 JavaScript 專案中的相依性。Yarn 可協助您安裝、更新、設定和移除套件相依性。

**程式碼儲存庫**

此模式的程式碼可在 GitHub [waitcondition-hook-for-aws-fargate-task](https://github.com/aws-samples/waitcondition-hook-for-aws-fargate-task) 儲存庫中使用。

## 最佳實務
<a name="use-the-aws-fargate-waitcondition-hook-construct-best-practices"></a>
+ 建置 AWS CDK 應用程式時，請遵循 AWS CDK v2 文件中的[使用 開發和部署雲端基礎設施的最佳實務 AWS CDK](https://docs.aws.amazon.com/cdk/v2/guide/best-practices.html)。
+ 針對 AWS Fargate 任務，請遵循 [Amazon ECS 文件中的 Amazon ECS 容器映像最佳實務](https://docs.aws.amazon.com/AmazonECS/latest/bestpracticesguide/application.html)。

## 史詩
<a name="use-the-aws-fargate-waitcondition-hook-construct-epics"></a>

### 設定 AWS CDK
<a name="set-up-the-cdk"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 安裝 AWS CDK。 | 若要 AWS CDK 在本機電腦或其他環境上安裝 ，請執行下列命令：<pre>npm install -g aws-cdk@latest</pre> | 雲端架構師、應用程式開發人員 | 
| 引導 AWS CDK。 | [引導](https://docs.aws.amazon.com/cdk/v2/guide/bootstrapping.html)是準備[環境](https://docs.aws.amazon.com/cdk/v2/guide/environments.html)以進行部署的程序。若要為目標引導 AWS CDK 您的工具組 AWS 區域， AWS 帳戶 並執行下列命令：<pre>cdk bootstrap aws://ACCOUNT-NUMBER-1/REGION-1 </pre>此命令會建立名為 的 CloudFormation 堆疊`CDKToolkit`。 | 雲端架構師 | 

### 執行 AWS Fargate 任務建構的 WaitCondition 掛鉤
<a name="run-the-waitcondition-hook-for-fargatelong-tasks-construct"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立 CDK 專案。 | 使用您偏好的語言建立 CDK 專案。此模式使用 TypeScript。若要使用 TypeScript 建立 CDK 專案，請執行下列命令：`cdk init app —language typescript` | 雲端架構師 | 
| 安裝套件。 | 在 CDK 專案的根路徑`npm install`上執行 。安裝 CDK 程式庫之後，請執行下列命令來安裝 `waitcondition-hook-for-aws-fargate-task`：`yarn add waitcondition-hook-for-aws-fargate-task` | 雲端架構師 | 
| 建置您的 CDK 應用程式和 Amazon ECS 元件。 | 建置您的 CDK 專案。需要 Amazon ECS 任務定義資源。如需建立任務定義的資訊，請參閱 [Amazon ECS 文件中的 Amazon ECS 任務定義](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definitions.html)。下列範例使用此建構：<pre>import * as cdk from 'aws-cdk-lib';<br />import { Vpc } from 'aws-cdk-lib/aws-ec2';<br />import * as ecr from 'aws-cdk-lib/aws-ecr';<br />import * as ecs from 'aws-cdk-lib/aws-ecs';<br />import { Construct } from 'constructs';<br />import { FargateRunner } from 'waitcondition-hook-for-aws-fargate-task';<br />import { Queue } from 'aws-cdk-lib/aws-sqs';<br /><br />export class FargateRunnerStack extends cdk.Stack {<br />    constructor(scope: Construct, id: string, props?: cdk.StackProps) {<br />        super(scope, id, props);<br />        // Define the VPC<br />        const vpc = new Vpc(this, 'MyVpc')<br />        // Define the Fargate Task<br />        const taskDefinition = new ecs.FargateTaskDefinition(this, 'MyTask', {});<br />        // Import exiting ecr repo<br />        const repo = ecr.Repository.fromRepositoryName(this, 'MyRepo', 'RepoName');<br />        // Add a container to the task<br />        taskDefinition.addContainer('MyContainer', {<br />            image: ecs.ContainerImage.fromEcrRepository(repo),<br />        });<br />        // Create the Fargate runner<br />        const myFargateRunner = new FargateRunner(this, 'MyRunner', {<br />            fargateTaskDef: taskDefinition,<br />            timeout: `${60 * 5}`,<br />            vpc: vpc,<br />        });<br />        // Create the SQS queue<br />        const myQueue = new Queue(this, 'MyQueue', {});<br />        // Add dependency<br />        myQueue.node.addDependency(myFargateRunner);<br />    }<br />}</pre> | 雲端架構師 | 
| 合成並啟動 CDK 應用程式。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/use-the-aws-fargate-waitcondition-hook-construct.html)建構執行 Fargate `waitcondition-hook-for-aws-fargate-task` 任務。 | 雲端架構師 | 

### 清除
<a name="clean-up"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 清除資源。 | 若要清除上一個步驟佈建的資源，請執行下列命令：<pre>cdk destroy </pre> | 雲端架構師 | 

## 疑難排解
<a name="use-the-aws-fargate-waitcondition-hook-construct-troubleshooting"></a>


| 問題 | 解決方案 | 
| --- | --- | 
| 一般 CloudFormation 堆疊失敗 | 若要協助疑難排解一般 CloudFormation 堆疊失敗，請新增 `--no-rollback`旗標，如下列範例所示：<pre>cdk deploy --no-rollback</pre>此命令會暫停 CloudFormation 堆疊的復原，讓您進行疑難排解。如需詳細資訊，請參閱在 CloudFormation 文件中[佈建資源時選擇如何處理失敗](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stack-failure-options.html)。 | 
| AWS Step Functions 失敗 |  AWS Step Functions 狀態機器可能會因不同原因而無法執行。`—disable-rollback` 設定 後，請使用下列步驟進行故障診斷：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/use-the-aws-fargate-waitcondition-hook-construct.html)如需詳細資訊，請參閱 AWS Step Functions 文件[中的 Step Functions 中的疑難排解問題](https://docs.aws.amazon.com/step-functions/latest/dg/troubleshooting.html)和 [Step Functions 主控台中的檢視執行詳細資訊](https://docs.aws.amazon.com/step-functions/latest/dg/concepts-view-execution-details.html#exec-details-intf-step-details)。 | 
| AWS Lambda 函數失敗 | 此建構模組會佈建兩個 Lambda 函數： `CallbackFunction`和 `ErrorhandlerFunction`。它們可能會因各種原因而失敗，例如未處理的例外狀況。使用下列步驟進行疑難排解：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/use-the-aws-fargate-waitcondition-hook-construct.html)如需詳細資訊，請參閱 AWS Lambda 文件中的[對 Lambda 中的問題進行故障診斷](https://docs.aws.amazon.com/lambda/latest/dg/lambda-troubleshooting.html)。 | 

## 相關資源
<a name="use-the-aws-fargate-waitcondition-hook-construct-resources"></a>

**AWS 文件**
+ [AWS CDK 建構 API 參考](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html)
+ [開始使用 AWS CDK](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html)
+ [了解如何建立和使用 Amazon ECS 資源](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/getting-started.html)
+ [了解如何開始使用 Step Functions](https://docs.aws.amazon.com/step-functions/latest/dg/getting-started-with-sfn.html)
+ [什麼是 AWS CDK？](https://docs.aws.amazon.com/cdk/v2/guide/home.html)

**其他資源**
+ [AWS Fargate 任務的等待條件掛接](https://pypi.org/project/waitcondition-hook-for-aws-fargate-task/) (npm)
+ [waitcondition-hook-for-aws-fargate-task 1.0.6](https://pypi.org/project/waitcondition-hook-for-aws-fargate-task/) (pypi.org：//)