

これは AWS CDK v2 デベロッパーガイドです。旧版の CDK v1 は 2022 年 6 月 1 日にメンテナンスを開始し、2023 年 6 月 1 日にサポートを終了しました。

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# CDK Toolkit Library を使用してプログラムによるアクションを実行する
<a name="toolkit-library"></a>

## CDK Toolkit Library を理解する
<a name="toolkit-library-intro"></a>

CDK Toolkit Library を使用すると、CLI コマンドを使用する代わりに、コードを使用して CDK のプログラムによるアクションを実行できます。このライブラリを使用して、カスタムツールの作成、特殊な CLI アプリケーションの構築、開発ワークフローへの CDK 機能の統合を行うことができます。

 **プログラムによる制御でインフラストラクチャのライフサイクルを管理する**   
CDK Toolkit Library には、次の CDK アクション用のプログラムによるインターフェイスが用意されています。  
+  **合成** - AWS CloudFormation テンプレートとデプロイアーティファクトを生成します。
+  **デプロイ** - CloudFormation テンプレートを使用してインフラストラクチャをプロビジョニングまたは更新します。
+  **リファクタリング** - コンストラクトの名前変更やスタック間の移動など、CDK コードのリファクタリング時にデプロイされたリソースを保持します。
+  **リスト** - スタックとその依存関係に関する情報を表示します。
+  **ウォッチ** - CDK アプリのローカルの変更をモニタリングします。
+  **ロールバック** - スタックを最後の安定状態に戻します。
+  **破棄** - CDK スタックと関連付けられたリソースを削除します。

 **インフラストラクチャ管理を強化およびカスタマイズする**   
+  **コードによって制御する** - インフラストラクチャ管理をアプリケーションに直接統合し、レスポンシブデプロイパイプラインを構築します。
+  **クラウドアセンブリを管理する** - デプロイ前にインフラストラクチャ定義を作成、検査、変換します。
+  **デプロイをカスタマイズする** - 要件に合わせてパラメータ、ロールバック動作、モニタリングを設定します。
+  **リファクタリング中にリソースを保持する** - CDK コードをリファクタリングするときにリソースを自動的に検出して保持します。
+  **エラーを正確に処理する** - 詳細な診断情報を使用して構造化されたエラー処理を実装します。
+  **通信をカスタマイズする** - カスタム進行状況インジケータを設定し、`IoHost` 実装を通じてログを記録します。
+  **AWS と接続する** - プロファイル、リージョン、認証フローをプログラムで設定します。

## CDK Toolkit Library を使用するタイミングの選択
<a name="toolkit-library-intro-when"></a>

CDK Toolkit Library は、以下を行う必要がある場合に特に役立ちます。
+ CI/CD パイプラインの一部としてインフラストラクチャのデプロイを自動化します。
+ 組織のニーズに合わせたカスタムデプロイツールを構築します。
+ CDK アクションを既存のアプリケーションまたはプラットフォームに統合します。
+ カスタム検証または承認ステップを使用して、特殊なデプロイワークフローを作成します。
+ 複数の環境全体で高度なインフラストラクチャ管理パターンを実装します。
+ リファクタリングオペレーションを自動化して、CDK コードをリファクタリングするときにリソースを保持します。

## CDK Toolkit Library の使用
<a name="toolkit-library-intro-example"></a>

次の例は、CDK Toolkit Library を使用してシンプルな S3 バケットを作成してデプロイする方法を示しています。

```
// Import required packages
import { Toolkit } from '@aws-cdk/toolkit-lib';
import { App, Stack } from 'aws-cdk-lib';
import * as s3 from 'aws-cdk-lib/aws-s3';

// Create and configure the CDK Toolkit
const toolkit = new Toolkit();

// Create a cloud assembly source with an inline app
const cloudAssemblySource = await toolkit.fromAssemblyBuilder(async () => {
   const app = new App();
   const stack = new Stack(app, 'SimpleStorageStack');

   // Create an S3 bucket in the stack
   new s3.Bucket(stack, 'MyFirstBucket', {
      versioned: true
   });

   return app.synth();
});

// Deploy the stack
await toolkit.deploy(cloudAssemblySource);
```

 **次のステップ**   
+  **デプロイを自動化する** - デプロイをプログラムによってトリガーし、デプロイ前後のステップを追加します。
+  **システムと統合する** - CI/CD ワークフロー、カスタムツール、モニタリングソリューションに接続します。
+  **デプロイの詳細を制御する** - スタック選択とマルチ環境デプロイのきめ細かなオプションを設定します。
+  **信頼性を強化する** - 本番環境対応のエラー処理とデプロイの進行状況の追跡を実装します。
+  **リファクタリングを自動化する** - CDK コードのリファクタリング時にリソースを検出して保存します。

## 次のステップ
<a name="toolkit-library-intro-next"></a>

CDK Toolkit Library の使用を開始するには、「[CDK Toolkit Library の使用を開始する](toolkit-library-gs.md)」を参照してください。

## 詳細
<a name="toolkit-library-intro-learn"></a>

Toolkit Library の詳細については、次の内容を参照してください。
+  *@aws-cdk/toolkit-lib* `npm` パッケージの [ReadMe](https://www.npmjs.com/package/@aws-cdk/toolkit-lib)。
+  [AWS CDK Toolkit Library API リファレンス](https://docs.aws.amazon.com/cdk/api/toolkit-lib/)。

# CDK Toolkit Library の使用を開始する
<a name="toolkit-library-gs"></a>

AWS CDK Toolkit Library を使用して開始し、コードで合成やデプロイなどの CDK アクションをプログラムで実行します。

## 前提条件
<a name="toolkit-library-gs-prerequisites"></a>

1. サポートされているバージョンの Node.js がインストールされました。

1.  AWS 認証情報が設定されています。

1. AWS CDK の基本的な知識。

詳細については、「[AWS CDK の前提条件](prerequisites.md)」を参照してください。

## ステップ 1: CDK Toolkit Library をインストールする
<a name="toolkit-library-gs-install"></a>

以下を実行して、プロジェクトの開発環境に CDK Toolkit Library パッケージをインストールします。

```
npm install --save @aws-cdk/toolkit-lib
```

## ステップ 2: CDK Toolkit Library を初期化する
<a name="toolkit-library-gs-initialize"></a>

CDK Toolkit インスタンスを作成して、CDK アプリでプログラムによるアクションを実行します。

```
import { Toolkit } from '@aws-cdk/toolkit-lib';

const toolkit = new Toolkit({
    // Optional configuration options go here
});
```

CDK Toolkit インスタンスは、作成時にカスタマイズできます。手順については、「[CDK Toolkit インスタンスの設定](toolkit-library-configure.md)」を参照してください。

## ステップ 3: CDK アプリのクラウドアセンブリソースを作成する
<a name="toolkit-library-gs-ca"></a>

クラウドアセンブリソースは、CDK アプリから CloudFormation テンプレートを生成する手順を提供します。複数の方法で 1 つを作成できます。以下に、いくつかの例を示します。

1.  **インラインアセンブリビルダー関数**:

   ```
   import * as cdk from 'aws-cdk-lib';
   
   const cloudAssemblySource = await toolkit.fromAssemblyBuilder(async () => {
     const app = new cdk.App();
     new MyStack(app, 'MyStack');
     return app.synth();
   });
   ```

1.  **既存の CDK アプリファイル**:

   ```
   const cloudAssemblySource = await toolkit.fromCdkApp("ts-node app.ts");
   ```

詳細については、「[クラウドアセンブリソースの設定](toolkit-library-configure-ca.md)」を参照してください。

## ステップ 4: CDK アプリのプログラムによるアクションを定義する
<a name="toolkit-library-gs-define"></a>

CDK Toolkit インスタンスとクラウドアセンブリソースを作成したので、プログラムによるアクションの定義を開始できます。`MyStack` スタックのデプロイを作成する基本的な例を次に示します。

```
import { StackSelectionStrategy } from '@aws-cdk/toolkit-lib';

await toolkit.deploy(cloudAssemblySource, {
  stacks: {
    strategy: StackSelectionStrategy.PATTERN_MUST_MATCH, // Deploy only stacks that exactly match the provided patterns
    patterns: ["MyStack"],
  },
});
```

## ステップ 5: CDK Toolkit をさらにカスタマイズする
<a name="toolkit-library-gs-customize"></a>

CDK Toolkit は、ニーズに合わせてさらに設定およびカスタマイズできます。
+  **メッセージとインタラクション** - CDK Toolkit がユーザーやアプリケーションと通信する方法を設定します。[メッセージとインタラクションの設定](toolkit-library-configure-messages.md)を参照してください。
+  **エラー処理** - CDK オペレーションの構造化エラー処理を実装します。「[エラー処理を設定する](toolkit-library-configure.md#toolkit-library-configure-errors)」を参照してください。。

## その他のリソース
<a name="toolkit-library-gs-resources"></a>

CDK Toolkit Library `npm` パッケージの詳細については、「*@aws-cdk/toolkit-lib* `npm` パッケージ」の「[ReadMe](https://www.npmjs.com/package/@aws-cdk/toolkit-lib)」を参照してください。

API リファレンス情報については、「[CDK Toolkit Library API リファレンス](https://docs.aws.amazon.com/cdk/api/toolkit-lib/)」を参照してください。

# CDK Toolkit のプログラムによるアクションの設定
<a name="toolkit-library-actions"></a>

AWS CDK Toolkit Library は、合成、デプロイ、スタック管理などのアプリケーションライフサイクルアクション用のプログラムによるインターフェイスを提供します。このガイドでは、コードで各アクションを使用する方法について説明します。

## synth を使用したクラウドアセンブリの生成
<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;
```

**ヒント**  
クラウドアセンブリを使用すると、合成が 1 回だけ行われるため、複数のオペレーションを実行する必要がある場合のパフォーマンスを最適化できます。キャッシュや廃棄など、クラウドアセンブリの管理の詳細については、「[クラウドアセンブリを作成して管理する](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 変更セットを使用するデフォルトのデプロイ方法を使用することをお勧めします。イテレーション速度が重要な開発環境では、ホットスワップなどの代替方法を使用できます。

```
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>

**重要**  
リファクタリングアクションはプレビューリリースであり、変更される可能性があります。

`refactor` アクションは、コンストラクトの名前変更やスタック間の移動などの CDK コードのリファクタリング時に、デプロイされたリソースを保持します。この機能がないと、これらの変更により、CloudFormation がリソースを置き換え、サービスの中断やデータ損失につながる可能性があります。

リファクタリングアクションでは、現在のコードをデプロイされた状態と比較することで、マッピングを自動的に計算します。CDK アプリケーションにデプロイされた状態とまったく同じリソースセットが含まれ、コンストラクトツリー内の場所のみが異なることを確認します。リソースの追加、削除、または変更が検出されると、リファクタリングオペレーションはエラーメッセージ付きで拒否されます。

マッピングを計算すると、リファクタリングアクションでは CloudFormation のリファクタリング API を使用して、リソース ID を置き換えずに更新します。あいまいなマッピング (複数のマッピングが存在する) が発生した場合は、明示的な上書きを指定してこれらのあいまいさを解決できます。

```
// 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 アプリのローカルファイルの変更を継続的にモニタリングし、デプロイまたはホットスワップを自動的に実行します。これにより、コードが終了するまで実行されるファイルウォッチャーが作成されます。

**警告**  
ホットスワップデプロイは、可能な場合は 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
  }
});
```

# CDK Toolkit インスタンスの設定
<a name="toolkit-library-configure"></a>

メッセージ処理、AWS プロファイル選択、およびスタック選択戦略のオプションを使用して AWS CDK Toolkit Library インスタンスをカスタマイズする方法について説明します。このガイドでは、使用可能な設定オプションと、特定のデプロイ要件を満たすためにそれらを効果的に実装する方法について説明します。

## AWS プロファイルの設定
<a name="toolkit-library-configure-profile"></a>

CDK Toolkit Library を使用すると、SDK を使用して AWS への 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" },
});
```

## スタック選択の設定
<a name="toolkit-library-configure-stacks"></a>

ほとんどの CDK Toolkit アクションでは、操作するスタックを指定する必要があります。` [StackSelector](https://docs.aws.amazon.com/cdk/api/toolkit-lib/Package/toolkit-lib/Interface/StackSelector/) ` 設定は、この選択を制御します。

### すべてのスタックセットを選択する
<a name="toolkit-library-configure-stacks-all"></a>

これは、CDK アプリ内のすべてのスタックで操作する場合に使用します。

```
import { StackSelectionStrategy } from '@aws-cdk/toolkit-lib';

// Select all stacks in the cloud assembly
await toolkit.deploy(cloudAssemblySource, {
  stacks: {
    strategy: StackSelectionStrategy.ALL_STACKS
  }
});
```

### メインアセンブリスタックのみを選択する
<a name="toolkit-library-configure-stacks-main"></a>

これを使用して、メインアセンブリから最上位スタックのみを選択します。

```
// Select only top-level stacks
await toolkit.deploy(cloudAssemblySource, {
  stacks: {
    strategy: StackSelectionStrategy.MAIN_ASSEMBLY
  }
});
```

### 1 つのスタックを選択する
<a name="toolkit-library-configure-stacks-single"></a>

これは、アセンブリにスタックが 1 つだけ含まれていて、この条件をアサートする場合に使用します。アセンブリに 1 つのスタックが含まれている場合、そのスタックが返されます。それ以外の場合は、例外がスローされます。

```
// Ensure there's exactly one stack and select it
await toolkit.deploy(cloudAssemblySource, {
  stacks: {
    strategy: StackSelectionStrategy.ONLY_SINGLE
  }
});
```

### パターンでスタックを選択する
<a name="toolkit-library-configure-stacks-pattern"></a>

これを使用して、名前パターンで特定のスタックを選択します。

```
// 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` を使用して、1 つのスタックがパターンと一致することを確認するか、スタックが一致しない場合は `PATTERN_MATCH` を使用します。パターンマッチングは、「\$1」などのワイルドカードをサポートし、類似した名前の複数のスタックを照合します。

## エラー処理の設定
<a name="toolkit-library-configure-errors"></a>

CDK Toolkit は、構造化エラーを使用して、問題の特定と処理を支援します。各エラーには以下が含まれます。
+ エラーの発生元 (ツールキットまたはユーザー) を示す**ソース**。
+ 特定の**エラータイプ** (認証、検証など)。
+ 記述的な**メッセージ**。

### エラー処理
<a name="toolkit-library-configure-errors-how"></a>

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 アクションの設定
<a name="toolkit-library-configure-actions"></a>

各 CDK Toolkit アクション (デプロイ、合成、リストなど) には、固有の設定オプションがあります。これらのアクションにより、CDK インフラストラクチャの完全なライフサイクルを管理できます。個々のアクションの設定の詳細については、「[CDK Toolkit のプログラムによるアクションを設定する](toolkit-library-actions.md)」を参照してください。

**ヒント**  
自動化ワークフローを構築するときは、複数のアクションを順番に組み合わせることを検討してください。例えば、アプリの `synth` 、デプロイされるものを検証するためのスタックの `list`、インフラストラクチャの `deploy` を行う場合があります。

# 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>

クラウドアセンブリを使用する場合は、次の 2 つのオプションがあります。

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 アプリは、オペレーション中に頻繁に変更されることはない。
+ より高速なパフォーマンスが必要である。

次の場合は、クラウドアセンブリソースを直接使用します。
+ 1 つのオペレーションを実行している。
+ CDK アプリが頻繁に変更される。
+ よりシンプルなコードが必要で、Toolkit のオペレーション速度を優先する必要はない。

**重要**  
パフォーマンスを向上させるには、ほとんどの Toolkit インタラクションでキャッシュされたアセンブリを使用する必要があります。キャッシュを回避する唯一のタイミングは、ソースが頻繁に変更され、変更の確認にコストがかかる場合です。

### クラウドアセンブリを作成、キャッシュ、再利用する方法
<a name="toolkit-library-configure-ca-cache-how"></a>

クラウドアセンブリソースを作成したら、クラウドアセンブリを合成することでそれを生成できます。クラウドアセンブリには、デプロイに必要な AWS CloudFormation テンプレートとアセットが含まれています。

クラウドアセンブリを 1 回生成し、複数の Toolkit オペレーションに再利用することをお勧めします。このキャッシュアプローチは、オペレーションごとにアセンブリを再生成するよりも効率的です。ソースが頻繁に変更される場合にのみ、アセンブリを再生成することを検討してください。

キャッシュされたクラウドアセンブリを作成する方法は次のとおりです。

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

その後、`list()`、`deploy()`、`diff()` など、キャッシュされたクラウドアセンブリでさまざまな Toolkit アクションを実行できます。クラウドアセンブリをキャッシュすることで、合成が 1 回だけ行われるため、後続の 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()` を使用してクラウドアセンブリを 1 回生成し、複数のオペレーションに再利用して、不要な合成、特に大規模なアプリケーションを回避します。
+  **エラー処理**: 基本的なエラー処理を実装して、エラーをキャッチしてユーザーに表示します。エラー処理をシンプルに保ち、明確なエラーメッセージを提供することに集中します。
+  **バージョンの互換性**: CDK Toolkit Library のバージョンが、使用しているクラウドアセンブリをサポートできることを確認します。クラウドアセンブリの作成に使用したコンストラクトライブラリが Toolkit Library でサポートされているものよりも新しい場合は、エラーが表示されます。
+  **環境変数**: 特定の環境変数はクラウドアセンブリの合成とデプロイに影響する可能性があることに注意してください。`CDK_DEFAULT_ACCOUNT`、`CDK_DEFAULT_REGION`、`CDK_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);
});
```

## 潜在的な問題の解決
<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();
}
```

# CDK Toolkit メッセージとインタラクションの設定
<a name="toolkit-library-configure-messages"></a>

AWS CDK Toolkit Library は、CDK オペレーション中のメッセージとインタラクションの処理方法をカスタマイズする ` [IIoHost](https://docs.aws.amazon.com/cdk/api/toolkit-lib/Package/toolkit-lib/Interface/IIoHost/) ` インターフェイスを提供します。これにより、デプロイの進行状況、エラーメッセージ、およびユーザープロンプトの表示を制御して、アプリケーションのユーザーエクスペリエンスと統合しやすくなります。

デプロイや合成などのオペレーションを実行する前に、CDK Toolkit がユーザーと通信する方法を理解しておく必要があります。`IIoHost` インターフェイスは、CDK Toolkit とアプリケーション間の通信チャネルとして機能し、送信メッセージと受信ユーザーレスポンスの両方を処理します。

CDK Toolkit がオペレーションを実行すると、2 つの主要なメカニズムを介して通信します。
+  **メッセージ**: オペレーションの進行状況 (「デプロイの開始」や「リソースの作成」など) を通知する情報出力。
+  **リクエスト**: 入力または確認が必要な決定ポイント (「これらの変更をデプロイしますか?」など) で、事前に必要であることがわからなかった情報を提供できます。

## `IIoHost` ユーザーインターフェイスの使用
<a name="toolkit-library-configure-messages-iiohost"></a>

`IIoHost` インターフェイスは 2 つの基本的な方法で構成されます。

1.  `notify`: 一方向の情報メッセージを処理します。

1.  `requestResponse`: レスポンスを必要とするインタラクティブリクエストを処理します。

```
import { IoMessage, IoRequest } from '@aws-cdk/toolkit-lib';

interface IIoHost {
  // Handle informational messages
  notify(message: IoMessage): Promise<void>;

  // Handle requests that need responses
  requestResponse(request: IoRequest): Promise<any>;
}
```

## メッセージレベルとリクエストタイプ
<a name="toolkit-library-configure-messages-levels"></a>

CDK Toolkit は、いくつかのタイプのメッセージとリクエストを生成します。

### メッセージレベル
<a name="_message_levels"></a>
+  **デバッグ**: トラブルシューティングの詳細メッセージ。
+  **エラー**: オペレーションに影響する可能性のあるエラーメッセージ。
+  **情報**: 一般的な情報メッセージ。
+  **結果** - オペレーションのプライマリメッセージ。
+  **トレース**: 非常に詳細な実行フロー情報。
+  **警告**: オペレーションを妨げない警告メッセージ。

詳細なリストについては、「*AWSCDK Toolkit Library API リファレンス*」の「[IoMessages レジストリ](https://docs.aws.amazon.com/cdk/api/toolkit-lib/message-registry/)」を参照してください。

### リクエストタイプ
<a name="_request_types"></a>

CDK Toolkit は、ユーザーからの入力または確認が必要な場合にリクエストを送信します。これらは、レスポンスを許可する特別なメッセージです。レスポンスが提供されない場合、Toolkit は利用可能な場合はデフォルトのレスポンスを使用します。

## 基本的な `IIoHost` の実装
<a name="toolkit-library-configure-messages-basic"></a>

カスタム io ホストを実装する簡単な例を次に示します。

```
import { Toolkit } from '@aws-cdk/toolkit-lib';

// Create a toolkit with custom message handling
const toolkit = new Toolkit({
  ioHost: {
    // Implementing the IIoHost interface
    // Handle informational messages
    notify: async function (msg) {
      // Example: Handle different message levels appropriately
      switch (msg.level) {
        case 'error':
          console.error(`[${msg.time}] ERROR: ${msg.message}`);
          break;
        case 'warning':
          console.warn(`[${msg.time}] WARNING: ${msg.message}`);
          break;
        case 'info':
          console.info(`[${msg.time}] INFO: ${msg.message}`);
          break;
        case 'debug':
          console.debug(`[${msg.time}] DEBUG: ${msg.message}`);
          break;
        case 'trace':
          console.debug(`[${msg.time}] TRACE: ${msg.message}`);
          break;
        default:
          console.log(`[${msg.time}] ${msg.level}: ${msg.message}`);
      }
    },

    // Handle requests that need responses
    requestResponse: async function (msg) {
      // Example: Log the request and use default response
      console.log(`Request: ${msg.message}, using default: ${msg.defaultResponse}`);
      return msg.defaultResponse;

      // Or implement custom logic to provide responses
      // if (msg.type === 'deploy') {
      //   return promptUserForDeployment(msg);
      // }
    }
  } as IIoHost // Explicitly cast to IIoHost interface
});
```

CDK Toolkit は各コールの完了を待機するため、メッセージを処理する際に HTTP リクエストやユーザープロンプトなどの非同期オペレーションを実行できます。

## デフォルトの `IIoHost` 動作
<a name="toolkit-library-configure-messages-iiohost-default"></a>

カスタム io ホストを提供しない場合、CDK Toolkit Library はデフォルトの非インタラクティブ実装を使用します。
+ メッセージのコンソール出力 (さまざまなメッセージタイプに適切な色を使用)。
+ ユーザー入力のプロンプトなしで、完全に非インタラクティブ。
+ 可能な場合は、デフォルトのレスポンスを自動的に使用します (プロンプトへの「はい」の回答に相当)。
+ 入力が必要であるけれども、デフォルトのレスポンスが利用できないときは失敗します。

このデフォルトの動作は、無人オペレーションに適していますが、インタラクティブなコマンドラインアプリケーションには適していません。ユーザーのインタラクションを必要とするコマンドラインアプリケーションの場合は、カスタム io ホストを実装する必要があります。カスタム実装は、ログ記録システム、UI、またはその他の特殊な環境との統合にも役立ちます。

## 高度な io ホスト実装
<a name="toolkit-library-configure-messages-advanced"></a>

より複雑なシナリオでは、開始点として `NonInteractiveIoHost` クラスを拡張することをお勧めします。このアプローチにより、変更する必要がある特定の動作のみをカスタマイズしながら、既存の非インタラクティブ実装を活用できます。

ベースとなる実装を拡張するカスタム io ホストの例を次に示します。

```
import { NonInteractiveIoHost } from '@aws-cdk/toolkit-lib';

class MyCustomIoHost extends NonInteractiveIoHost {
  // Override only the methods you need to customize

  // Example: Custom implementation for notify
  public async notify(msg: IoMessage<unknown>): Promise<void> {
    // Add custom notification handling logic
    if (msg.level === 'error') {
      console.error(`ERROR: ${msg.message}`);
      // Optionally log to a service or notify a monitoring system
      await this.logToMonitoringService(msg);
    } else {
      await super.notify(msg);
    }
  }

  // Example: Custom implementation for requestResponse
  public async requestResponse<T, U>(request: IoRequest<T, U>): Promise<U> {
    // Implement custom request handling
    console.log(`Received request: ${request.message}`);
    return request.defaultResponse;
  }

  private async logToMonitoringService(msg: IoMessage<unknown>): Promise<void> {
    // Implementation for monitoring service integration
    console.log(`Logging to monitoring service: ${msg.level} - ${msg.message}`);
  }
}
```

このアプローチは、カスタム動作を必要とする特定のメソッドを上書きするだけで済むため、`IIoHost` インターフェイス全体を最初から実装するよりもメンテナンスしやすくなります。

## さまざまな環境との統合
<a name="toolkit-library-configure-messages-integration"></a>

### ウェブアプリケーション統合
<a name="_web_application_integration"></a>

```
import { Toolkit } from '@aws-cdk/toolkit-lib';

// Example for integrating with a web application
const toolkit = new Toolkit({
  ioHost: {
    notify: async function (msg) {
      // Send message to frontend via WebSocket
      webSocketServer.send(JSON.stringify({
        type: 'cdk-notification',
        messageLevel: msg.level,
        message: msg.message,
        time: msg.time
      }));
    },

    requestResponse: async function (msg) {
      // Create a promise that will be resolved when the user responds
      return new Promise((resolve) => {
        const requestId = generateUniqueId();

        // Store the resolver function
        pendingRequests[requestId] = resolve;

        // Send request to frontend
        webSocketServer.send(JSON.stringify({
          type: 'cdk-request',
          requestId: requestId,
          requestType: msg.type,
          message: msg.message,
          defaultResponse: msg.defaultResponse
        }));

        // Frontend would call an API endpoint with the response,
        // which would then call pendingRequests[requestId](response)
      });
    }
  } as IIoHost // Explicitly cast to IIoHost interface
});
```

### CI/CD 環境統合
<a name="_cicd_environment_integration"></a>

```
import { Toolkit } from '@aws-cdk/toolkit-lib';

// Example for CI/CD environments (non-interactive)
const toolkit = new Toolkit({
  ioHost: {
    notify: async function (msg) {
      // Log all messages with appropriate level
      switch (msg.level) {
        case 'error':
          console.error(msg.message);
          break;
        case 'warning':
          console.warn(msg.message);
          break;
        default:
          console.log(msg.message);
      }
    },

    requestResponse: async function (msg) {
      // In CI/CD, always use default responses or predefined answers
      console.log(`Auto-responding to request: ${msg.message} with ${msg.defaultResponse}`);
      return msg.defaultResponse;
    }
  } as IIoHost // Explicitly cast to IIoHost interface
});
```

## io ホスト実装のベストプラクティス
<a name="toolkit-library-configure-messages-best-practices"></a>

カスタム io ホストを実装するときは、次のベストプラクティスを考慮してください。
+  **エラー処理**: io ホストメソッドに堅牢なエラー処理を実装して、障害が CDK オペレーションに影響を与えないようにします。
+  **タイムアウト**: 無期限の待機を防ぐために、ユーザーインタラクションのタイムアウトを実装することを検討してください。
+  **ログ記録**: 特に非インタラクティブ環境では、トラブルシューティングのために重要なメッセージをログに保存します。
+  **デフォルトレスポンス**: ユーザーインタラクションが不可能な自動環境には、適切なデフォルトレスポンスを提供します。
+  **進行状況の表示**: 長時間実行されるオペレーションの場合は、明確な進行状況インジケータを提供してユーザーエクスペリエンスを向上させます。

次の例は、エラー処理、ユーザーインタラクションのタイムアウト、および適切なログ記録を備えたカスタム io ホストを実装することで、これらのベストプラクティスを示しています。この実装は、ユーザーの応答性と信頼性の高いオペレーションのバランスを取る必要があるインタラクティブなアプリケーションに適しています。

```
import { Toolkit } from '@aws-cdk/toolkit-lib';

// Example with error handling and timeouts
const toolkit = new Toolkit({
  ioHost: {
    notify: async function (msg) {
      try {
        console.log(`[${msg.time}] ${msg.level}: ${msg.message}`);
        // Additional logging or UI updates
      } catch (error) {
        // Ensure errors in notification handling don't break the CDK operation
        console.error("Error handling notification:", error);
      }
    },

    requestResponse: async function (msg) {
      try {
        // Implement timeout for user response
        const response = await Promise.race([
          getUserResponse(msg),
          new Promise(resolve => setTimeout(() => resolve(msg.defaultResponse), 60000))
        ]);
        return response;
      } catch (error) {
        console.error("Error handling request:", error);
        return msg.defaultResponse;
      }
    }
  } as IIoHost // Explicitly cast to IIoHost interface
});
```

## トラブルシューティング
<a name="toolkit-library-configure-messages-troubleshooting"></a>

カスタム io ホストを実装する際の考慮事項:
+  **未処理の promise 拒否**: すべての非同期オペレーションが try/catch ブロックで適切に処理されていることを確認します。
+  **無限待機**: アプリケーションがハングしないように、すべてのユーザーインタラクションのタイムアウトを実装します。
+  **メッセージレベルの欠落**: 将来の CDK バージョンで追加される可能性のある新しいメッセージレベルを処理する準備をします。
+  **一貫性のないレスポンス**: requestResponse 実装が、想定された形式で値を返すことを確認します。

次の例は、今後の CDK バージョンで導入される可能性のある未知のメッセージタイプの適切な処理など、メッセージレベルを処理するための堅牢なアプローチを示しています。この実装により、適切なログ記録を維持しながら、io ホストと CDK 更新との互換性が維持されます。

```
import { Toolkit } from '@aws-cdk/toolkit-lib';

// Example of handling unknown message levels
const toolkit = new Toolkit({
  ioHost: {
    notify: async function (msg) {
      // Handle known levels
      const knownLevels = ['info', 'warning', 'error', 'debug', 'trace', 'status'];

      if (knownLevels.includes(msg.level)) {
        // Handle known level
        handleKnownMessageLevel(msg);
      } else {
        // Handle unknown level as info
        console.log(`Unknown message level "${msg.level}": ${msg.message}`);
      }
    },

    requestResponse: async function (msg) {
      // Default implementation
      return msg.defaultResponse;
    }
  } as IIoHost // Explicitly cast to IIoHost interface
});
```

# 高度な CDK Toolkit Library の例
<a name="toolkit-library-examples"></a>

実用的な例を使用して、AWS CDK Toolkit Library の高度な機能を使用する方法について説明します。このガイドでは、他のセクションで説明されている基本概念に基づいて構築された、エラー処理、デプロイモニタリング、クラウドアセンブリ管理の詳細なコードサンプルを提供します。

## 機能の統合
<a name="toolkit-library-examples-integration"></a>

次の例は、クラウドアセンブリソース、カスタム IO ホスト実装、およびデプロイオプションを組み合わせる方法を示しています。

```
import { Toolkit, StackSelectionStrategy, IIoHost } from '@aws-cdk/toolkit-lib';

async function deployApplication(appPath, environment, options = {}) {
  // Create toolkit with custom message handling
  const toolkit = new Toolkit({
    ioHost: {
      notify: async (msg) => {
        // Add environment to all messages
        console.log(`[${environment}][${msg.time}] ${msg.level}: ${msg.message}`);
      },
      requestResponse: async (msg) => {
        // In production environments, use default responses
        if (environment === 'production') {
          console.log(`Auto-approving for production: ${msg.message}`);
          return msg.defaultResponse;
        }

        // For other environments, implement custom approval logic
        return promptForApproval(msg);
      }
    } as IIoHost
  });

  try {
    // Create cloud assembly source from the CDK app
    console.log(`Creating cloud assembly source from ${appPath}`);
    const cloudAssemblySource = await toolkit.fromCdkApp(appPath);

    // Synthesize the cloud assembly
    console.log(`Synthesizing cloud assembly`);
    const cloudAssembly = await toolkit.synth(cloudAssemblySource);

    try {
      // Deploy with environment-specific options
      console.log(`Deploying to ${environment} environment`);
      return await toolkit.deploy(cloudAssembly, {
        stacks: options.stacks || { strategy: StackSelectionStrategy.ALL_STACKS },
        parameters: options.parameters || {},
        tags: {
          Environment: environment,
          DeployedBy: 'CDK-Toolkit-Library',
          DeployTime: new Date().toISOString()
        }
      });
    } finally {
      // Always dispose when done
      await cloudAssembly.dispose();
    }
  } catch (error) {
    console.error(`Deployment to ${environment} failed:`, error);
    throw error;
  }
}

// Example usage
await deployApplication('ts-node app.ts', 'staging', {
  parameters: {
    MyStack: {
      InstanceType: 't3.small'
    }
  }
});
```

## デプロイの進行状況の追跡
<a name="toolkit-library-examples-progress"></a>

詳細なステータス更新を使用してデプロイの進行状況を追跡します。

```
import { Toolkit, StackSelectionStrategy, IIoHost } from '@aws-cdk/toolkit-lib';

// Create a progress tracker
class DeploymentTracker {
  private startTime: Date;
  private resources = new Map<string, string>();

  constructor() {
    this.startTime = new Date();
  }

  onStackEvent(stackName: string, event: string, timestamp: string) {
    // Calculate elapsed time if needed, or use the provided timestamp
    const elapsed = (new Date().getTime() - this.startTime.getTime()) / 1000;
    console.log(`[${timestamp}] (${elapsed.toFixed(1)}s elapsed) Stack ${stackName}: ${event}`);
  }

  onResourceEvent(resourceId: string, status: string) {
    this.resources.set(resourceId, status);
    this.printProgress();
  }

  private printProgress() {
    console.log('\nResource Status:');
    for (const [id, status] of this.resources.entries()) {
      console.log(`- ${id}: ${status}`);
    }
    console.log();
  }
}

// Use the tracker with the toolkit
const tracker = new DeploymentTracker();
const toolkit = new Toolkit({
  ioHost: {
    notify: async (msg) => {
      if (msg.code.startsWith('CDK_DEPLOY')) {
        // Track deployment events
        if (msg.data && 'stackName' in msg.data) {
          tracker.onStackEvent(msg.data.stackName, msg.message, msg.time);
        }
      } else if (msg.code.startsWith('CDK_RESOURCE')) {
        // Track resource events
        if (msg.data && 'resourceId' in msg.data) {
          tracker.onResourceEvent(msg.data.resourceId, msg.message);
        }
      }
    }
  } as IIoHost
});

// Example usage with progress tracking
async function deployWithTracking(cloudAssemblySource: any) {
  try {
    // Synthesize the cloud assembly
    const cloudAssembly = await toolkit.synth(cloudAssemblySource);

    try {
      // Deploy using the cloud assembly
      await toolkit.deploy(cloudAssembly, {
        stacks: {
          strategy: StackSelectionStrategy.ALL_STACKS
        }
      });
    } finally {
      // Always dispose when done
      await cloudAssembly.dispose();
    }
  } catch (error) {
    // Display the error message
    console.error("Operation failed:", error.message);
    throw error;
  }
}
```

## 復旧によるエラーの処理
<a name="toolkit-library-examples-error"></a>

復旧戦略を使用して堅牢なエラー処理を実装します。

```
import { Toolkit, ToolkitError, StackSelectionStrategy } from '@aws-cdk/toolkit-lib';

async function deployWithRetry(toolkit: Toolkit, cloudAssemblySource: any) {
  try {
    // Synthesize the cloud assembly
    const cloudAssembly = await toolkit.synth(cloudAssemblySource);

    try {
      // Deploy using the cloud assembly
      await toolkit.deploy(cloudAssembly, {
        stacks: {
          strategy: StackSelectionStrategy.ALL_STACKS
        }
      });
    } finally {
      // Always dispose when done
      await cloudAssembly.dispose();
    }
  } catch (error) {
    // Simply show the error to the user
    console.error("Operation failed:", error.message);
    throw error;
  }
}

// Example usage
try {
  await deployWithRetry(toolkit, cloudAssemblySource);
} catch (error) {
  console.error("Operation failed:", error.message);
  process.exit(1);
}
```

## CI/CD パイプラインとの統合
<a name="toolkit-library-examples-cicd"></a>

CDK Toolkit Library を CI/CD パイプラインに統合します。

```
import { Toolkit, StackSelectionStrategy, IIoHost } from '@aws-cdk/toolkit-lib';
import * as fs from 'fs';
import * as path from 'path';

async function cicdDeploy() {
  // Create a non-interactive toolkit for CI/CD environments
  const toolkit = new Toolkit({
    ioHost: {
      notify: async (msg) => {
        // Write to both console and log file
        const logMessage = `${msg.time} [${msg.level}] ${msg.message}`;
        console.log(logMessage);

        // Append to deployment log file
        fs.appendFileSync('deployment.log', logMessage + '\n');
      },
      requestResponse: async (msg) => {
        // Always use default responses in CI/CD
        console.log(`Auto-responding to: ${msg.message} with: ${msg.defaultResponse}`);
        return msg.defaultResponse;
      }
    } as IIoHost
  });

  // Determine environment from CI/CD variables
  const environment = process.env.DEPLOYMENT_ENV || 'development';

  // Load environment-specific parameters
  const paramsPath = path.join(process.cwd(), `params.${environment}.json`);
  const parameters = fs.existsSync(paramsPath)
    ? JSON.parse(fs.readFileSync(paramsPath, 'utf8'))
    : {};

  try {
    // Use pre-synthesized cloud assembly from build step
    const cloudAssemblySource = await toolkit.fromAssemblyDirectory('cdk.out');

    // Synthesize the cloud assembly
    const cloudAssembly = await toolkit.synth(cloudAssemblySource);

    try {
      // Deploy with CI/CD specific options
      const result = await toolkit.deploy(cloudAssembly, {
        stacks: { strategy: StackSelectionStrategy.ALL_STACKS },
        parameters,
        tags: {
          Environment: environment,
          BuildId: process.env.BUILD_ID || 'unknown',
          CommitHash: process.env.COMMIT_HASH || 'unknown'
        }
      });

      // Write outputs to a file for subsequent pipeline steps
      fs.writeFileSync(
        'stack-outputs.json',
        JSON.stringify(result.outputs, null, 2)
      );

      return result;
    } finally {
      // Always dispose when done
      await cloudAssembly.dispose();
    }
  } catch (error) {
    // Display the error message
    console.error("Operation failed:", error.message);
    process.exit(1);
  }
}

// Run the CI/CD deployment
cicdDeploy().then(() => {
  console.log('CI/CD deployment completed successfully');
});
```

## その他のリソース
<a name="toolkit-library-examples-resources"></a>

これらの例で使用される特定のコンポーネントの詳細については、以下を参照してください。
+  [クラウドアセンブリソースの管理](toolkit-library-configure-ca.md) - クラウドアセンブリソースを作成および管理する方法を説明します。
+  [メッセージとインタラクションの設定](toolkit-library-configure-messages.md) - `IIoHost` インターフェイスのカスタマイズに関する詳細なガイド。