這是 AWS CDK v2 開發人員指南。較舊的 CDK v1 已於 2022 年 6 月 1 日進入維護,並於 2023 年 6 月 1 日結束支援。
本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
設定您的 CDK Toolkit 執行個體
了解如何使用訊息處理、 AWS 設定檔選擇和堆疊選擇策略的選項來自訂 AWS CDK Toolkit Library 執行個體。本指南說明可用的組態選項,以及如何有效實作這些選項,以符合您的特定部署需求。
設定您的 AWS 設定檔
當您使用 CDK Toolkit Library 時,它會 AWS 使用 SDK 對 進行 API 呼叫。從您的環境自動載入身分驗證時,您可以明確指定要使用的設定檔:
import { Toolkit } from '@aws-cdk/toolkit-lib'; // Create a toolkit instance with a specific AWS profile const toolkit = new Toolkit({ sdkConfig: { profile: "my-profile" }, });
設定堆疊選取
大多數 CDK Toolkit 動作要求您指定要操作的堆疊。 StackSelector
組態會控制此選項。
選取所有堆疊
當您想要在 CDK 應用程式的每個堆疊上操作 時,請使用此選項:
import { StackSelectionStrategy } from '@aws-cdk/toolkit-lib'; // Select all stacks in the cloud assembly await toolkit.deploy(cloudAssemblySource, { stacks: { strategy: StackSelectionStrategy.ALL_STACKS } });
僅選取主要組件堆疊
使用此選項僅從主要組件中選取最上層堆疊:
// Select only top-level stacks await toolkit.deploy(cloudAssemblySource, { stacks: { strategy: StackSelectionStrategy.MAIN_ASSEMBLY } });
選取單一堆疊
當您的組件只包含一個堆疊,而且您想要宣告此條件時,請使用此選項。如果組件包含單一堆疊,則會傳回該堆疊。否則,它會擲回例外狀況:
// Ensure there's exactly one stack and select it await toolkit.deploy(cloudAssemblySource, { stacks: { strategy: StackSelectionStrategy.ONLY_SINGLE } });
依模式選取堆疊
使用此選項依名稱模式選取特定堆疊:
// Select stacks matching specific patterns await toolkit.deploy(cloudAssemblySource, { stacks: { strategy: StackSelectionStrategy.PATTERN_MUST_MATCH, patterns: ["Dev-*", "Test-Backend"], // Supports wildcards } });
提示
使用 PATTERN_MUST_MATCH_SINGLE
來確保一個堆疊完全符合您的模式,或者PATTERN_MATCH
如果沒有堆疊可以符合的話。模式比對支援「*」等萬用字元,以比對具有類似名稱的多個堆疊。
設定錯誤處理
CDK Toolkit 使用結構化錯誤來協助您識別和處理問題。每個錯誤包括:
-
指出錯誤來源的來源 (工具組或使用者)。
-
特定錯誤類型 (身分驗證、驗證等)。
-
描述性訊息。
處理錯誤
使用 CDK Toolkit 提供的協助程式方法來偵測和處理特定錯誤類型:
import { ToolkitError } from '@aws-cdk/toolkit-lib'; try { // Attempt a CDK Toolkit operation await toolkit.deploy(cloudAssemblySource, { stacks: { strategy: StackSelectionStrategy.ALL_STACKS } }); } catch (error) { // Handle specific error types if (ToolkitError.isAuthenticationError(error)) { // Example: AWS credentials are missing or invalid console.error('Authentication failed. Check your AWS credentials.'); } else if (ToolkitError.isAssemblyError(error)) { // Example: Your CDK app has errors in stack definitions console.error('CDK app error:', error.message); } else if (ToolkitError.isDeploymentError(error)) { // Example: CloudFormation deployment failed console.error('Deployment failed:', error.message); } else if (ToolkitError.isToolkitError(error)) { // Handle all other Toolkit errors console.error('CDK Toolkit error:', error.message); } else { // Handle unexpected errors console.error('Unexpected error:', error); } }
重要
不要依賴instanceof
檢查錯誤類型,因為在使用相同套件的多個副本時,它們可能會意外地發生。一律使用提供的協助程式方法,例如 ToolkitError.isAuthenticationError()
。
設定 Toolkit 動作
每個 CDK Toolkit 動作 (部署、合成、清單等) 都有自己的特定組態選項。這些動作可讓您管理 CDK 基礎設施的完整生命週期。如需設定個別動作的詳細資訊,請參閱設定 CDK Toolkit 程式設計動作。
提示
建置自動化工作流程時,請考慮依序組合多個動作。例如,您可能想要synth
您的應用程式、用於驗證將部署哪些項目的list
堆疊,以及deploy
基礎設施。