

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

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

# 管理 AWS CDK Toolkit Library 雲端組件來源
<a name="toolkit-library-configure-ca"></a>

使用 AWS CDK Toolkit Library 設定雲端組件來源，並自訂您部署 CDK 應用程式的方式。本指南說明如何設定雲端組件來源，以符合您的部署需求和工作流程需求。

使用 CDK Toolkit 之前，請指定雲端組件來源。*雲端組件來源*提供從 CDK 應用程式產生雲端組件的說明。產生的雲端組件包含 CDK Toolkit 部署到的合成基礎設施成品 AWS。

CDK Toolkit Library 提供多種方法來設定雲端組件來源，每個都適用於不同的案例和工作流程。

## 選取雲端組件來源
<a name="toolkit-library-configure-ca-options"></a>


| 方法 | 最適合 | 考量事項 | 
| --- | --- | --- | 
|   `fromCdkApp`   |  使用任何支援的語言處理現有的 CDK 應用程式。  |  需要安裝適當的語言執行時間。  | 
|   `fromAssemblyBuilder`   |  建立 CDK 建構內嵌並完全控制合成程序。  |  提供 CDK 功能的低階存取權，可用於建置其他方法的自訂版本，例如 `fromCdkApp`。  | 
|   `fromAssemblyDirectory`   |  使用預先合成的雲端組件。  |  跳過合成步驟時，執行速度更快。  | 
|  自訂來源  |  需要完整自訂實作的極端專業案例。  |  需要從頭開始實作`ICloudAssemblySource`界面；缺少內建功能，例如內容查詢；在大多數使用案例中很少需要。  | 

## 設定您的雲端組件來源
<a name="toolkit-library-configure-ca-how"></a>

### 從現有的 CDK 應用程式
<a name="toolkit-library-configure-ca-how-app"></a>

使用 `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");
```

### 從內嵌組件建置器
<a name="toolkit-library-configure-ca-how-builder"></a>

使用組件建置器函數直接在程式碼中建立 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']
});
```

### 從現有的組件目錄
<a name="toolkit-library-configure-ca-how-directory"></a>

如果您已有合成的雲端組件，您可以直接使用它。當您已執行`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']
});
```

## 使用快取的雲端組件
<a name="toolkit-library-configure-ca-cache"></a>

使用雲端組件時，您有兩個選項：

1. 直接使用雲端組件來源 （簡單但可能較慢）：

   ```
   // Each operation triggers a new synthesis
   await toolkit.deploy(cloudAssemblySource, { /* options */ });
   await toolkit.list(cloudAssemblySource, { /* options */ });
   ```

1. 快取雲端組件 （多個操作速度更快）：

   ```
   // 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 互動應使用快取的組件來提升效能。避免快取的唯一時間是，當您的來源經常變更，並且檢查變更會很昂貴時。

### 如何建立、快取和重複使用雲端組件
<a name="toolkit-library-configure-ca-cache-how"></a>

建立雲端組件來源之後，您可以透過合成雲端組件來產生雲端組件。雲端組件包含部署所需的 AWS CloudFormation 範本和資產。

我們建議您產生一次雲端組件，並將其重複使用於多個 Toolkit 操作。這種快取方法比為每個操作重新產生組件更有效率。只有當您的來源經常變更時，才考慮重新產生組件。

以下是如何建立快取雲端組件的方法：

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

然後，您可以在快取的雲端組件上執行各種 Toolkit 動作，例如 `list()`、 `deploy()`和 `diff()`。透過快取雲端組件，後續 Toolkit 動作的執行速度會更快，因為合成只會發生一次。如需詳細資訊，請參閱[語法 - 產生雲端組件](toolkit-library-actions.md#toolkit-library-actions-synth)。

### 處置雲端組件資源
<a name="toolkit-library-configure-ca-cache-dispose"></a>

當您完成使用雲端組件來清除臨時資源時，請務必將其處置。我們建議您使用 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();
}
```

### 了解雲端組件生命週期
<a name="toolkit-library-configure-ca-cache-lifetime"></a>

當您使用 建立快取的雲端組件時`synth()`，您會取得同時做為可讀取`CloudAssembly`和 的特殊類型`CloudAssemblySource`。從此快取組件產生的任何雲端組件 （例如，從清單或部署操作） 都會繫結至父系的生命週期：
+ 只有父系的 dispose() 呼叫會實際清除資源
+ 來自清單/部署操作的雲端組件由其父系管理
+ 無法處置快取的雲端組件視為錯誤

## 雲端組件來源的最佳實務
<a name="toolkit-library-configure-ca-best-practices"></a>

使用雲端組件來源時，請考慮下列最佳實務：
+  **選擇正確的來源方法**：選取最符合您工作流程和需求的方法。
+  **快取雲端組件**：使用 產生一次雲端組件，`synth()`並重複使用於多個操作，以避免不必要的合成，尤其是大型應用程式。
+  **錯誤處理**：實作基本錯誤處理，以擷取並顯示錯誤給使用者。保持簡單的錯誤處理，並專注於提供明確的錯誤訊息。
+  **版本相容性**：確保您的 CDK Toolkit Library 版本可以支援您正在使用的雲端組件。如果用來建立雲端組件的 Construct Library 比 Toolkit Library 支援的版本更新，您會收到錯誤。
+  **環境變數**：請注意，某些環境變數可能會影響雲端組件合成和部署。`CDK_DEFAULT_ACCOUNT`、`CDK_OUTDIR`、 `CDK_DEFAULT_REGION`和 等變數`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);
});
```

## 解決潛在問題
<a name="toolkit-library-configure-ca-troubleshooting"></a>

請依照下列步驟來解決雲端組件來源的潛在問題：
+  **安裝缺少的相依性**：執行 `npm install` 以安裝 CDK 應用程式所需的相依性。
+  **修正路徑問題**：檢查 CDK 應用程式和組件目錄的路徑是否存在且可供存取。
+  **解決版本不符**：更新您的 CDK Toolkit Library 版本以符合您的 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();
}
```