

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 使用 AWS Fargate WaitCondition 挂钩构造协调资源依赖关系和任务执行
<a name="use-the-aws-fargate-waitcondition-hook-construct"></a>

*Stan Fan，Amazon Web Services*

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

此模式描述了 WaitCondition hook (`waitcondition-hook-for-aws-fargate-task`) npm 包，它是一种云原生解决方案，专为在亚马逊弹性容器服务 (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 挂钩提供以下关键功能：
+ 充当等待条件机制，在指定的 Fargate 任务完成之前暂停 CloudFormation 堆栈执行，这有助于有序部署和资源配置。
+ 支持 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 和 npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-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)，然后选择相应服务的链接。

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

下图显示了此构造的架构。

![\[-f waitcondition-hook-for-aws argate-task 结构的 AWS Step Functions 工作流程。\]](http://docs.aws.amazon.com/zh_cn/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. 根据任务的结果，完成 Fargate 任务之后将会触发 `CallbackFunction` 或 `ErrorHandlerFunction`。

1. Lambda 函数将向 `WaitConditionHandler` 发送一个“成功”或“失败”信号。

1. 如果 Fargate 任务的执行结果成功，`WaitConditionHandler` 会继续预调配资源；如果任务失败，将回滚堆栈。

下图显示了一个用于执行数据库迁移的工作流的示例。

![\[使用 WaitCondition 钩子构造迁移 Amazon RDS 数据库的工作流程。\]](http://docs.aws.amazon.com/zh_cn/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。否则，它会向堆栈发送 Fail 信号，然后回滚堆栈。 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（亚马逊 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-](https://github.com/aws-samples/waitcondition-hook-for-aws-fargate-task) 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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 安装 AWS CDK。 | 要 AWS CDK 在本地计算机或其他环境中安装，请运行以下命令：<pre>npm install -g aws-cdk@latest</pre> | 云架构师、应用程序开发人员 | 
| Bootstrap 的。 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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 CDK 项目。 | 使用您的首选语言创建一个 CDK 项目。此模式使用 TypeScript. 要使用创建 CDK 项目 TypeScript，请运行以下命令：`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_cn/prescriptive-guidance/latest/patterns/use-the-aws-fargate-waitcondition-hook-construct.html)`waitcondition-hook-for-aws-fargate-task` 构造将运行 Fargate 任务。 | 云架构师 | 

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 清理资源。 | 要清理上一步中预调配的资源，请运行如下命令：<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_cn/prescriptive-guidance/latest/patterns/use-the-aws-fargate-waitcondition-hook-construct.html)有关更多信息，请参阅 AWS Step Functions 文档中的 Step F [unctions 中的问题疑难解答](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_cn/prescriptive-guidance/latest/patterns/use-the-aws-fargate-waitcondition-hook-construct.html)有关更多信息，请参阅文档[中的 Lambda 问题疑难解答](https://docs.aws.amazon.com/lambda/latest/dg/lambda-troubleshooting.html)。 AWS Lambda  | 

## 相关资源
<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](https://pypi.org/project/waitcondition-hook-for-aws-fargate-task/) 1.0.6 (pypi.org)