これは AWS CDK v2 デベロッパーガイドです。旧版の CDK v1 は 2022 年 6 月 1 日にメンテナンスを開始し、2023 年 6 月 1 日にサポートを終了しました。
翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。
CDK Toolkit プログラムによるアクションの設定
AWS CDK Toolkit Library は、合成、デプロイ、スタック管理などのアプリケーションライフサイクルアクション用のプログラムインターフェイスを提供します。このガイドでは、コードで各アクションを使用する方法について説明します。
同期を使用したクラウドアセンブリの生成
synth
アクションは、クラウドアセンブリソースからクラウドアセンブリを生成します。合成の詳細については、「CDK スタック合成の設定と実行」を参照してください。クラウドアセンブリには、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 回だけ行われるため、複数のオペレーションを実行する必要がある場合のパフォーマンスを最適化できます。キャッシュや廃棄など、クラウドアセンブリの管理の詳細については、「クラウドアセンブリの作成と管理」を参照してください。
リストを使用したスタック情報の表示
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}`); }
デプロイによるインフラストラクチャのプロビジョニング
deploy
アクションは、合成中に生成されたクラウドアセンブリ AWS を使用して、 のインフラストラクチャをプロビジョニングまたは更新します。デプロイの概要については、AWS 「CDK アプリケーションのデプロイ」を参照してください。スタックの選択、パラメータ値、ロールバック動作などのデプロイオプションを制御できます。
// 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"] } });
ロールバックによる失敗したデプロイの復元
デプロイが失敗し、自動的に元に戻すことができない場合、 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"] } });
watch による変更のモニタリング
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()
メソッドを呼び出します。
破棄によるインフラストラクチャの削除
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 } });