管理 AWS CDK 工具包库云程序集源 - AWS Cloud Development Kit (AWS CDK) v2

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

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

管理 AWS CDK 工具包库云程序集源

使用 AWS CDK 工具包库配置云程序集源并自定义 CDK 应用程序的部署方式。本指南向您介绍如何配置云装配源以满足您的部署要求和工作流程需求。

在使用 CDK 工具包之前,请指定云程序集源。云程序集源提供了从 CDK 应用程序生成云程序集的说明。生成的云程序集包含 CDK Toolkit 部署到的合成基础架构工件。 AWS

CDK Toolkit 库提供了多种配置云装配源的方法,每种方法都适用于不同的场景和工作流程。

选择云端装配源

方法 最适合 考虑因素

fromCdkApp

使用任何支持的语言处理现有 CDK 应用程序。

需要安装相应的语言运行时。

fromAssemblyBuilder

在完全控制合成过程的情况下在线创建 CDK 构造。

提供对 CDK 功能的低级访问权限,可用于构建其他方法的自定义版本,例如. fromCdkApp

fromAssemblyDirectory

使用预先合成的云组件。

由于跳过了合成步骤,因此执行速度更快。

自定义来源

需要完全自定义实现的极其专业的场景。

需要从头开始实现ICloudAssemblySource接口;缺少上下文查找等内置功能;大多数用例很少需要。

配置您的云端装配源

从现有的 CDK 应用程序中获得

使用该fromCdkApp方法处理以任何支持的语言编写的 CDK 应用程序。当您有现有 CDK 应用程序并希望以编程方式部署它时,这种方法非常理想。

import { App } from 'aws-cdk-lib'; import { Toolkit } from '@aws-cdk/toolkit-lib'; // Create a toolkit instance const toolkit = new Toolkit(); // TypeScript app const cloudAssemblySource = await toolkit.fromCdkApp("ts-node app.ts"); // Deploy a specific stack from the assembly await toolkit.deploy(cloudAssemblySource, { stacks: ['MyStack'] }); // Other language examples: // JavaScript app // const cloudAssemblySource = await toolkit.fromCdkApp("node app.js"); // Python app // const cloudAssemblySource = await toolkit.fromCdkApp("python app.py"); // Java app // const cloudAssemblySource = await toolkit.fromCdkApp("mvn -e -q exec:java -Dexec.mainClass=com.mycompany.app.App");

来自内联汇编生成器

使用汇编生成器函数直接在代码中创建 CDK 应用程序。这种方法对于想要内联定义基础架构的简单部署或测试场景非常有用。

import { App, Stack, RemovalPolicy, StackProps } from 'aws-cdk-lib'; import { Bucket } from 'aws-cdk-lib/aws-s3'; import { Toolkit } from '@aws-cdk/toolkit-lib'; import { Construct } from 'constructs'; // Create a cloud assembly source from an inline CDK app const cloudAssemblySource = await toolkit.fromAssemblyBuilder(async () => { const app = new App(); // Define a simple stack with an S3 bucket class MyStack extends Stack { constructor(scope: Construct, id: string, props?: StackProps) { super(scope, id, props); // Create an S3 bucket new Bucket(this, 'MyBucket', { versioned: true, removalPolicy: RemovalPolicy.DESTROY, autoDeleteObjects: true }); } } // Instantiate the stack new MyStack(app, 'MyInlineStack'); return app.synth(); }); // Deploy using the cloud assembly source await toolkit.deploy(cloudAssemblySource, { stacks: ['MyInlineStack'] });

从现有的程序集目录中

如果您已经有了合成的云组件,则可以直接使用它。当你已经运行过cdk synth或者处理由 CI/CD 管道生成的云程序集时,这很有用。

import { Toolkit } from '@aws-cdk/toolkit-lib'; // Create a toolkit instance const toolkit = new Toolkit(); // Use an existing cloud assembly directory const cloudAssemblySource = await toolkit.fromAssemblyDirectory("cdk.out"); // Deploy using the cloud assembly source await toolkit.deploy(cloudAssemblySource, { stacks: ['MyStack'] });

使用缓存的云程序集

使用云程序集时,您有两个选择:

  1. 直接使用云端程序集源(简单但可能较慢):

    // Each operation triggers a new synthesis await toolkit.deploy(cloudAssemblySource, { /* options */ }); await toolkit.list(cloudAssemblySource, { /* options */ });
  2. 缓存云程序集(多项操作更快):

    // Synthesize once and reuse const cloudAssembly = await toolkit.synth(cloudAssemblySource); try { // Multiple operations use the same assembly await toolkit.deploy(cloudAssembly, { /* options */ }); await toolkit.list(cloudAssembly, { /* options */ }); } finally { // Clean up when done await cloudAssembly.dispose(); }

在以下情况下使用缓存的程序集:

  • 您正在执行多个操作(部署、列出、差异等)。

  • 您的 CDK 应用程序在操作期间不会经常更改。

  • 你想要更快的性能。

在以下情况下直接使用云端程序集源:

  • 您正在执行一项操作。

  • 您的 CDK 应用程序经常更改。

  • 你想要更简单的代码,不需要优先考虑 Toolkit 的操作速度。

重要

为了提高性能,大多数 Toolkit 交互都应使用缓存的程序集。避免缓存的唯一时间是源代码经常更改并且检查更改会很昂贵的时候。

如何创建、缓存和重复使用云端程序集

创建云组件源后,可以通过合成云组件来生成云组件。云程序集包含部署所需的 AWS CloudFormation 模板和资产。

我们建议您生成一次云程序集,然后将其重复用于多个 Toolkit 操作。这种缓存方法比为每个操作重新生成程序集更有效。请考虑仅在源频繁更改时才重新生成组件。

以下是创建缓存的云程序集的方法:

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

然后,您可以对缓存的云程序集执行各种 Toolkit 操作list(),例如deploy()、和diff()。通过缓存云端程序集,可以更快地执行后续的 Toolkit 操作,因为合成只发生一次。有关更多信息,请参阅 synth-生成云程序集

处置云端装配资源

使用完云程序集清理临时资源后,请务必将其处置。我们建议使用 try/finally 块来确保正确清理,尤其是在执行多个操作时:

// Generate a cloud assembly const cloudAssembly = await toolkit.synth(cloudAssemblySource); try { // Use the cloud assembly for multiple operations await toolkit.list(cloudAssembly); await toolkit.deploy(cloudAssembly); } finally { // Always dispose when done await cloudAssembly.dispose(); }

以下示例展示了如何创建和处置缓存的云程序集:

import { Toolkit } from '@aws-cdk/toolkit-lib'; const toolkit = new Toolkit(); // Create cloud assembly source from a CDK app const cloudAssemblySource = await toolkit.fromCdkApp("ts-node app.ts"); // Create cloud assembly from source const cloudAssembly = await toolkit.synth(cloudAssemblySource); try { // List stacks in the assembly await toolkit.list(cloudAssembly); // Check for changes await toolkit.diff(cloudAssembly); // Deploy if needed await toolkit.deploy(cloudAssembly); } finally { // Always dispose when done await cloudAssembly.dispose(); }

了解云装配生命周期

当你使用创建缓存的云程序集时synth(),你会得到一种特殊的类型,它既是可读的,又是可读CloudAssemblyCloudAssemblySource。从此缓存的程序集(例如,列表或部署操作)生成的任何云程序集都与父程序集的生命周期相关联:

  • 只有父级的 dispose () 调用才能真正清理资源

  • 列表/部署操作中的云程序集由其父程序集管理

  • 未能处置缓存的云程序集被视为错误

云端装配源的最佳实践

使用云装配源时,请考虑以下最佳实践:

  • 选择正确的来源方法:选择最适合您的工作流程和要求的方法。

  • 缓存云程序集:使用一次即可生成云程序集,synth()然后将其重复用于多个操作,以避免不必要的合成,尤其是对于大型应用程序。

  • 错误处理:实现基本的错误处理,以捕获错误并向用户显示错误。保持错误处理的简单性,并专注于提供清晰的错误信息。

  • 版本兼容性:确保您的 CDK Toolkit 库版本可以支持您正在使用的云程序集。如果用于创建云程序集的构造库比您的 Toolkit 库支持的版本更新,则会收到错误消息。

  • 环境变量:请注意,某些环境变量可能会影响云程序集的合成和部署。诸如CDK_DEFAULT_ACCOUNTCDK_DEFAULT_REGIONCDK_OUTDIR、和之类的变量CDK_CONTEXT_JSON可以覆盖默认行为。确保这些设置适合您的部署环境。

以下示例演示了在重复使用云程序集进行多个操作时如何实现错误处理和适当的清理:

import { Toolkit } from '@aws-cdk/toolkit-lib'; // Example with error handling and proper cleanup async function deployInfrastructure(): Promise<void> { let cloudAssembly; try { // Generate a cloud assembly once cloudAssembly = await toolkit.synth(cloudAssemblySource); // Reuse the same cloud assembly for multiple operations await toolkit.list(cloudAssembly); // Uses existing assembly await toolkit.deploy(cloudAssembly); // Uses existing assembly await toolkit.diff(cloudAssembly); // Uses existing assembly } catch (error) { console.error("Failed to deploy:", error); } finally { // Always dispose when done if (cloudAssembly) { await cloudAssembly.dispose(); } } } // Call the async function deployInfrastructure().catch(error => { console.error("Deployment failed:", error); process.exit(1); });

解决潜在问题

请按照以下步骤解决云装配源的潜在问题:

  • 安装缺少的依赖项:运行npm install以安装 CDK 应用程序所需的依赖项。

  • 修复路径问题:检查 CDK 应用程序和汇编目录的路径是否存在并且可以访问。

  • 解决版本不匹配问题:更新您的 CDK 工具包库版本以匹配您的 CDK 应用程序版本。

  • 修复合成错误:检查您的 CDK 应用程序代码中是否存在语法错误或无效配置。

当 Toolkit 操作期间出现错误时,请简化错误处理,并专注于向用户提供清晰的错误消息。使用完云程序集后,请务必将其丢弃。以下示例展示了通过正确清理进行基本错误处理:

import { Toolkit } from '@aws-cdk/toolkit-lib'; // Example with simple error handling try { // Create the cloud assembly source const cloudAssemblySource = await toolkit.fromCdkApp("ts-node app.ts"); // Synthesize the cloud assembly const cloudAssembly = await toolkit.synth(cloudAssemblySource); // Use the cloud assembly await toolkit.list(cloudAssembly); } catch (error) { // Display the error message console.error("Operation failed:", error.message); } finally { // Clean up resources await cloudAssembly.dispose(); }