

这是 AWS CDK v2 开发者指南。旧版 CDK v1 于 2022 年 6 月 1 日进入维护阶段，并于 2023 年 6 月 1 日终止支持。

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

# 配置 CDK 工具包编程操作
<a name="toolkit-library-actions"></a>

AWS CDK 工具包库为应用程序生命周期操作（例如合成、部署和堆栈管理）提供编程接口。本指南说明如何在代码中使用每个操作。

## 使用 synth 生成云程序集
<a name="toolkit-library-actions-synth"></a>

`synth` 操作会根据您的云程序集源生成云程序集。有关合成的更多信息，请参阅[配置和执行 CDK 堆栈合成](configure-synth.md)。云程序集包含以下来自 CDK 应用程序的部署构件：
+  用于定义基础设施的 AWS CloudFormation 模板。
+ 资产，例如 Lambda 函数代码或 Docker 映像。
+ 部署元数据和配置。

下面介绍了如何使用 `synth` 操作创建云程序集：

```
// Create a toolkit instance
const toolkit = new Toolkit();

// Create a cloud assembly source from a TypeScript app
const cloudAssemblySource = await toolkit.fromCdkApp("ts-node app.ts");

// Generate a cloud assembly
const cloudAssembly = await toolkit.synth(cloudAssemblySource);

// Use the cloud assembly for operations
await toolkit.list(cloudAssembly);
await toolkit.deploy(cloudAssembly);
await toolkit.diff(cloudAssembly);

// Query information from the cloud assembly
const template = cloudAssembly.getStack("my-stack").template;
```

**提示**  
使用云程序集可以优化性能，尤其是在需要执行多个操作时，因为合成只进行一次。有关管理云程序集（包括缓存和处置）的更多信息，请参阅[创建和管理云程序集](toolkit-library-configure-ca.md#toolkit-library-configure-ca-cache)。

## 使用 list 查看堆栈信息
<a name="toolkit-library-actions-list"></a>

`list` 操作会检索 CDK 应用程序中堆栈的相关信息，包括其依赖项和当前状态。使用此操作可在部署前检查基础设施或生成报告。

```
import { StackSelectionStrategy } from '@aws-cdk/toolkit-lib';

// Get information about specific stacks
const stackDetails = await toolkit.list(cloudAssemblySource, {
  stacks: {
    strategy: StackSelectionStrategy.PATTERN_MUST_MATCH,
    patterns: ["my-stack"], // Only include stacks matching this pattern
  }
});

// Process the returned stack information
for (const stack of stackDetails) {
  console.log(`Stack: ${stack.id}, Dependencies: ${stack.dependencies}`);
}
```

## 使用 deploy 预置基础设施
<a name="toolkit-library-actions-deploy"></a>

`deploy` 操作使用合成期间生成的云程序集在 AWS 中预置或更新您的基础设施。有关部署的介绍，请参阅[部署 AWS CDK 应用程序](deploy.md)。您可以控制堆栈选择、参数值和回滚行为等部署选项。

```
// Deploy stacks with parameter values
await toolkit.deploy(cloudAssemblySource, {
  parameters: StackParameters.exactly({
    "MyStack": {
      "BucketName": "amzn-s3-demo-bucket"
    }
  })
});
```

部署操作支持不同的部署方法以适应各种工作流。对于大多数场景，尤其是在生产环境中，我们建议使用默认部署方法，其使用 CloudFormation 更改集。对于迭代速度很重要的开发环境，您可以使用热交换等替代方法。

```
import { StackSelectionStrategy } from '@aws-cdk/toolkit-lib';

// Deploy using default deployment method (recommended for production)
await toolkit.deploy(cloudAssemblySource, {
  parameters: StackParameters.exactly({
    "MyStack": {
      "BucketName": "amzn-s3-demo-bucket"
    }
  })
});

// For development environments only: Deploy with hotswap for faster iterations
// Note: We recommend using default deployment methods for production environments
await toolkit.deploy(cloudAssemblySource, {
  deploymentMethod: { method: "hotswap", fallback: true }, // Faster but introduces drift
  stacks: {
    strategy: StackSelectionStrategy.PATTERN_MUST_MATCH,
    patterns: ["dev-stack"]
  }
});
```

## 使用 refactor 保留已部署的资源
<a name="toolkit-library-actions-refactor"></a>

**重要**  
refactor 操作目前为预览版，可能会发生变化。

`refactor` 操作可在您重构 CDK 代码（例如，重命名构造或在堆栈之间移动构造）时保留已部署的资源。如果没有此功能，这些更改将导致 CloudFormation 替换资源，进而可能导致服务中断或数据丢失。

refactor 操作会将当前代码与已部署状态进行比较，从而自动计算映射。它验证您的 CDK 应用程序是否包含与已部署状态完全相同的资源集，只是它们在构造树中的位置不同。如果检测到任何资源添加、删除或修改，则重构操作将被拒绝并显示一条错误消息。

计算映射后，refactor 操作会使用 CloudFormation 的重构 API 来更新资源的逻辑 ID，而无需替换资源本身。如果遇到模糊映射（存在多个可能的映射），您可以提供显式覆盖来解决这些歧义。

```
// Perform refactoring operation to preserve resources
await toolkit.refactor(cloudAssemblySource);

// With optional overrides to resolve ambiguities
await toolkit.refactor(cloudAssemblySource, {
  overrides: {
    "environments": [
      {
        "account": "123456789012",
        "region": "us-east-2",
        "resources": {
          "StackA.OldName": "StackA.NewName"
        }
      }
    ]
  }
});
```

**重要**  
重构操作必须与其他操作（例如，添加新资源、删除资源或修改资源属性）分开执行。如果需要进行此类更改，应先单独部署这些更改，然后再使用重构来重新组织资源。

**提示**  
有关 CDK 重构的更多信息（包括其工作原理和何时使用），请参阅[重构 CDK 代码时保留已部署的资源](refactor.md)。

## 使用 rollback 恢复失败的部署
<a name="toolkit-library-actions-rollback"></a>

当部署失败且无法自动撤消时，`rollback` 操作会将堆栈恢复到其最后一个稳定状态。使用此操作可从需要人工干预的失败部署中恢复。

```
import { StackSelectionStrategy } from '@aws-cdk/toolkit-lib';

// Roll back stacks to their last stable state
await toolkit.rollback(cloudAssemblySource, {
  orphanFailedResources: false, // When true, removes failed resources from CloudFormation management
  stacks: {
    strategy: StackSelectionStrategy.PATTERN_MUST_MATCH,
    patterns: ["failed-stack"]
  }
});
```

## 使用 watch 监控更改
<a name="toolkit-library-actions-watch"></a>

`watch` 操作会持续监控 CDK 应用程序的本地文件更改，并自动执行部署或热交换。这将创建一个文件监视器，该监视器会一直运行，直到您的代码退出或终止。

**警告**  
热交换部署会尽可能直接更新资源，而无需通过 CloudFormation 进行，从而在开发过程中加快更新速度。默认情况下，`watch` 命令会启用此功能。虽然这可以加快开发周期，但会导致 CloudFormation 模板和已部署资源之间出现偏差。因此，我们建议您不要在生产环境中使用热交换。

```
import { StackSelectionStrategy } from '@aws-cdk/toolkit-lib';

// Start watching for changes
const watcher = await toolkit.watch(cloudAssemblySource, {
  include: ["lib/**/*.ts"], // Only watch TypeScript files in the lib directory
  exclude: ["**/*.test.ts"], // Ignore test files
  deploymentMethod: { method: "hotswap" }, // This is the default, shown here for clarity
  stacks: {
    strategy: StackSelectionStrategy.ALL // Watch all stacks
  }
});

// Later in your code, you can explicitly stop watching:
// await watcher.dispose();
```

watch 函数会返回一个 `IWatcher` 对象，允许您显式控制何时停止监视。当您想要结束监视进程时，请对此对象调用 `dispose()` 方法。

## 使用 destroy 移除基础设施
<a name="toolkit-library-actions-destroy"></a>

`destroy` 操作会从 AWS 中移除 CDK 堆栈及其关联资源。当不再需要资源时，可使用此操作清理资源。

**重要**  
与此命令的 CLI 版本不同，destroy 操作会永久移除资源，而不会提示确认。在销毁堆栈之前，请务必备份所有重要数据。

```
import { StackSelectionStrategy } from '@aws-cdk/toolkit-lib';

// Remove specific stacks and their resources
await toolkit.destroy(cloudAssemblySource, {
  stacks: {
    strategy: StackSelectionStrategy.PATTERN_MUST_MATCH,
    patterns: ["dev-stack"], // Only destroy stacks matching this pattern
  }
});
```