配置 CDK 工具包编程操作 - AWS Cloud Development Kit (AWS CDK) v2

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

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

配置 CDK 工具包编程操作

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

使用 synth 生成云程序集

synth操作会从您的云装配源生成云装配。有关合成的更多信息,请参见配置和执行 CDK 堆栈合成。云程序集包含来自 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;
提示

当你需要执行多项操作时,使用云程序集可以优化性能,因为合成只发生一次。有关管理云程序集(包括缓存和处置)的更多信息,请参阅创建和管理云程序集

使用列表查看堆栈信息

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操作 AWS 使用合成期间生成的云程序集来配置或更新您的基础架构。有关部署的介绍,请参阅部署 AWS CDK 应用程序。您可以控制部署选项,例如堆栈选择、参数值和回滚行为。

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

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

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"] } });

通过重构保留已部署的资源

重要

重构操作处于预览版,可能会发生变化。

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

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

计算映射后,重构操作将使用 CloudFormation其重构 API 来更新资源的逻辑 IDs ,而无需替换它们。如果它遇到模糊的映射(存在多个可能的映射),则可以提供显式替代来解决这些歧义。

// 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 代码时保留已部署的资源

使用回滚恢复失败的部署

当部署失败且无法自动撤消时,该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操作会持续监视您的 CDK 应用程序的本地文件更改,并自动执行部署或热交换。这将创建一个文件观察器,该监视器一直运行到您的代码退出或终止。

警告

Hotswap 部署无需在可能的情况下直接更新资源,从而 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操作会从中移除 CDK 堆栈及其相关资源。 AWS使用此操作可在不再需要资源时清理资源。

重要

与该命令的 CLI 版本不同,销毁操作会在不提示确认的情况下永久删除资源。在销毁堆栈之前,请确保有所有重要数据的备份。

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 } });