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

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

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

配置 CDK 工具包编程操作

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

使用合成器生成云程序集

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

使用回滚恢复失败的部署

当部署失败且无法自动撤消时,该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 } });