這是 AWS CDK v2 開發人員指南。較舊的 CDK v1 已於 2022 年 6 月 1 日進入維護,並於 2023 年 6 月 1 日結束支援。
本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
設定 CDK Toolkit 程式設計動作
AWS CDK Toolkit Library 為合成、部署和堆疊管理等應用程式生命週期動作提供程式設計界面。本指南說明如何在程式碼中使用每個動作。
使用語法產生雲端組件
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();
監看函數會傳回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 } });