

這是 AWS CDK v2 開發人員指南。較舊的 CDK v1 已於 2022 年 6 月 1 日進入維護，並於 2023 年 6 月 1 日結束支援。

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 設定 CDK Toolkit 程式設計動作
<a name="toolkit-library-actions"></a>

 AWS CDK Toolkit Library 為合成、部署和堆疊管理等應用程式生命週期動作提供程式設計界面。本指南說明如何在程式碼中使用每個動作。

## 使用語法產生雲端組件
<a name="toolkit-library-actions-synth"></a>

`synth` 動作會從雲端組件來源產生雲端組件。如需合成的詳細資訊，請參閱[設定和執行 CDK 堆疊合成](configure-synth.md)。雲端組件包含來自 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;
```

**提示**  
當您需要執行多個操作時，使用雲端組件可以最佳化效能，因為合成只會發生一次。如需管理雲端組件的詳細資訊，包括快取和處置，請參閱[建立和管理雲端組件](toolkit-library-configure-ca.md#toolkit-library-configure-ca-cache)。

## 使用清單檢視堆疊資訊
<a name="toolkit-library-actions-list"></a>

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

## 使用 部署佈建基礎設施
<a name="toolkit-library-actions-deploy"></a>

`deploy` 動作 AWS 會使用合成期間產生的雲端組件，在 中佈建或更新基礎設施。如需部署的簡介，請參閱[部署 AWS CDK 應用程式](deploy.md)。您可以控制部署選項，例如堆疊選擇、參數值和回復行為。

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

## 使用重構來保留已部署的資源
<a name="toolkit-library-actions-refactor"></a>

**重要**  
重構動作處於預覽版本中，可能會有所變更。

當您重構 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 程式碼時保留已部署的資源](refactor.md)。

## 使用轉返還原還原失敗的部署
<a name="toolkit-library-actions-rollback"></a>

當部署失敗且無法自動反轉時， `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"]
  }
});
```

## 使用 監看監控變更
<a name="toolkit-library-actions-watch"></a>

`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()`方法。

## 使用銷毀移除基礎設施
<a name="toolkit-library-actions-destroy"></a>

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