

これは 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>

クラウドアセンブリを使用する場合は、次の 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();
}
```