AWS インフラストラクチャを CDK(クラウド開発キット)と TypeScript または Python を使用して作成・デプロイ・トラブルシューティングするスキルです。ベストプラクティス、スタック(インフラの構成単位)アーキテクチャ、コンストラクト(再利用可能な部品)パターンをカバーしています。 次のような場合に使用: CDK コンストラクトを記述する、環境をセットアップする、cdk deploy/synth/diff コマンドを実行する、CDK または CloudFormation のエラーを修正する、スタック構造を計画する、既存のリソースをインポートする、ドリフト(意図しない変更)を解決する、またはリソースを置き換えずにスタックをリファクタリングする場合。
Authors, deploys, and troubleshoots AWS infrastructure using CDK with TypeScript or Python. Covers best practices, stack architecture, and construct patterns. Applies when writing CDK constructs, bootstrapping environments, running cdk deploy/synth/diff, fixing CDK or CloudFormation errors, planning stack structure, importing existing resources, resolving drift, or refactoring stacks without resource replacement.
CDK(AWS Cloud Development Kit)コンストラクト(再利用可能な部品)の作成、デプロイ、法令対応、ドリフト検出(実際のリソースとコードのズレ)、リソースのインポート、安全なコード修正、および CDK CLI / CloudFormation エラーの解決に関する専門知識を提供します。
使用しないべき場合: 生の CloudFormation YAML/JSON、SAM、Terraform/Pulumi、CDK Pipelines 以外の CI/CD(継続的インテグレーション・デリバリー)。これらについては、組み込み知識または専用スキルを使用してください。
クロススタック参照の削除はデプロイを停止させる: クロススタック参照(複数のスタック間のリンク)を削除すると、デプロイが停止します(Export ... cannot be deleted as it is in use by ...というエラーが出ます)。推奨される対策: まず参照を弱くする — CrossStackReferences.of($RESOURCE).produce(ReferenceStrength.BOTH) → WEAK → 削除(3回のデプロイが必要)。以前の方法: 2回のデプロイを使う this.exportValue() の方式。詳細は troubleshooting-deployment を参照。
コンストラクト ID の変更はリソース置き換えを招く: コンストラクトの名前変更または移動で論理 ID が変わり → CloudFormation がリソースを置き換える(ステートフル(状態を持つ)リソースではデータが失われます)。デプロイ前に必ず cdk diff を実行してください。詳細は refactor-and-prevent-replacement を参照。
UPDATE_ROLLBACK_FAILED: スタックが停止状態: cdk rollback $STACK または cdk rollback $STACK --orphan <LogicalId> で修正できます。Express モード(高速デプロイモード)スタックは例外で、ロールバック不可です。詳細は troubleshooting-deployment を参照。
Hotswap(部分的な更新)と Express モードは開発環境のみ: --hotswap / --hotswap-fallback は CloudFormation をバイパスして意図的にドリフトを生じさせます;--express はリソースが安定する前に成功を報告し、自動ロールバックを無効にします。本番環境では使用禁止です。失敗した --express デプロイはロールバックできません。別の --express デプロイで修正を加えて進める必要があります。詳細は fast-deployments を参照。
空でない S3 バケットは削除後も残る: removalPolicy: DESTROY と autoDeleteObjects: true を両方設定する必要があります。バージョン管理されたバケットはさらに複雑です。削除済みマーカーが見かけ上の削除後も残ります。
| 作業 | コマンド | 詳細 |
|---|---|---|
| ブートストラップ(初期設定) | cdk bootstrap aws://$ACCOUNT/$REGION |
bootstrap-and-project-setup |
| 新規 TypeScript プロジェクト | cdk init app --language typescript — tsx と eslint-plugin-awscdk を使用 |
bootstrap-and-project-setup |
| 新規 Python プロジェクト | cdk init app --language python — 依存関係を固定化し、virtualenv を使用 |
bootstrap-and-project-setup |
| デプロイ | cdk synth --strict → cdk diff → cdk deploy |
本番デプロイ前に必ず差分確認 |
| 高速開発イテレーション | cdk deploy --hotswap-fallback、cdk watch、または cdk deploy --express — 開発のみ、本番は禁止 |
fast-deployments |
| cdk-nag(法令対応チェック) | Aspects.of(app).add(new AwsSolutionsChecks()) |
compliance-and-drift |
| ドリフト検出 | cdk drift $STACK(CI では --fail を使用) |
compliance-and-drift |
| リソースをインポート | cdk import(対話型またはCI用 --resource-mapping)、cdk deploy --import-existing-resources |
import-and-migrate |
| 安全にコードを修正 | cdk refactor --unstable=refactor — 同じデプロイで プロパティを変更しない |
refactor-and-prevent-replacement |
どちらも安全性と速度をトレードオフしており、本番環境では使用禁止です。
どちらを選ぶか: ホットスワップ対応リソース(更新時に停止しないリソース)を主に使い、ドリフトが問題でない場合は --hotswap / --hotswap-fallback を使用。ドリフトが許されない、またはリソースがホットスワップ非対応の場合は --express を使用。
ドリフト復旧方法(--revert-drift 経由の Hotswap ドリフト解消、失敗した --express デプロイの前進、ホットスワップ対応リソールール、本番禁止の IAM・監視制御など詳細は完全ガイドを参照: fast-deployments。
| エラー | 原因 → 対策 |
|---|---|
| DeployFailed / DeploymentError | CDK エラーは根本原因ではありません。cdk deploy $STACK --verbose を実行し、cdk --unstable=diagnose diagnose $STACK(CLI ≥ 2.1120.0)を実行;それ以外は aws cloudformation describe-events --stack-name $STACK --filters FailedEvents=true — 最初の _FAILED イベントが原因。詳細 |
| NoCredentials / ExpiredToken / AssumeRoleFailed | aws sts get-caller-identity + cdk doctor を実行。SSO 期限切れ、env 欠落、sts:AssumeRole 欠落。詳細 |
| アセット(資産)エラー(CannotFindAsset、FailedToBundleAsset、AssetBuildFailed、AssetPublishFailed) | パス間違い、Docker 未起動、またはブートストラップバケットの権限不足。path.join(__dirname, ...) を使用。詳細 |
| AppRequired | cdk.json に "app": "npx tsx bin/my-app.ts" を追加。詳細 |
| AnnotationErrors | 根本的な問題を修正;抑制は NagSuppressions で最後の手段としてのみ。詳細 |
| ConcurrentReadLock / ConcurrentWriteLock | rm -rf cdk.out を実行して再実行。並列 CI: --output ./cdk.out.$BUILD_ID を使用。詳細 |
| BootstrapVersionValidation | ブートストラップを再実行。--qualifier をすべての場所で一致させる。詳細 |
| DependencyCycle | 共有リソースを第 3 のスタックに抽出するか、遅延バインディング用に SSM を使用。詳細 |
| UnresolvedAccount | スタックで明示的に env: { account, region } を設定。cdk.context.json をコミット。詳細 |
| NoStacksMatched | CDK は CloudFormation 名ではなく論理 ID(コンストラクタの第 2 引数)を使用。cdk list で ID を確認。詳細 |
| Cannot find module(合成時) | npx tsc --noEmit を実行、cdk.json のアプリパスが tsconfig.json の outDir と一致することを確認、古い .js ファイルを削除。Python: venv をアクティブ化。詳細 |
| V1 インポートパス / 重複した aws-cdk-lib | V1 の @aws-cdk/* インポート、Construct インポート不正、モノレポの重複ライブラリコピー。詳細 |
| Lambda Cannot find module(実行時) | ハンドラ値が間違っている、AWS SDK v3 への移行漏れ、Python の依存関係がバンドルされていない。詳細 |
| API Gateway マルチステージ競合 | RestApi に deploy: false を設定、Deployment と Stage を明示的に作成。詳細 |
--hotswap で変更がデプロイされない |
ホットスワップ非対応リソースへの変更は静かに無視され、ログにのみ記録されます。コマンドは成功を報告します。出力を確認し、CloudFormation デプロイを強制するには --hotswap-fallback を使用。詳細 |
失敗した --express デプロイ / ロールバック不可 |
Express モード は Rollback Stack API を使用できず、標準デプロイで復旧してはいけません。前進で修正: 原因を修正後、cdk deploy $STACK --express を実行。詳細 |
| 開発スタックの予期しないドリフト | Hotswap と cdk watch は意図的にドリフトを生じさせます。復旧するまで、CloudFormation の記録ではなく、ライブリソース(実際のリソース)が本体です。cdk deploy $STACK --revert-drift で調整(Drift Aware Changesets を使用して、ライブリソースをテンプレートと一致させます。CloudFormation 記録をドリフトされたリソースと一致させるのではなく、現実を希望状態に更新)。詳細 |
L2(高レベル)を優先。L2 にプロパティがない場合は、Mixin/Facade で L1(低レベル)を使用。エスケープハッチ: node.defaultChild → addPropertyOverride。詳細は construct-patterns を参照。
--custom-permissions-boundary を使用grant*() メソッドを使用cdk-nag + --strict を使用terminationProtection: true を設定cdk.context.json をコミットDomain expertise for CDK construct authoring, deployment workflows, compliance, drift, importing resources, safe refactoring, and troubleshooting CDK CLI / CloudFormation errors.
When NOT to use: Raw CloudFormation YAML/JSON. SAM. Terraform/Pulumi. CI/CD beyond CDK Pipelines. Use builtin knowledge or specialized skills for these.
Deadly embrace: Removing a cross-stack reference deadlocks deployment (Export ... cannot be deleted as it is in use by ...). Preferred fix: weaken the reference first — CrossStackReferences.of($RESOURCE).produce(ReferenceStrength.BOTH) then WEAK, then remove (three deploys). Legacy fallback: two-deploy this.exportValue() recipe. See troubleshooting-deployment.
Construct ID changes cause replacement: Renaming/moving a construct changes its logical ID → CloudFormation replaces the resource (data loss for stateful resources). Always cdk diff before deploy. See refactor-and-prevent-replacement.
UPDATE_ROLLBACK_FAILED: Stack is stuck. Fix with cdk rollback $STACK or cdk rollback $STACK --orphan <LogicalId>. Express mode stacks are the exception — they cannot be rolled back at all. See troubleshooting-deployment.
Hotswap and express mode are development-only: --hotswap / --hotswap-fallback bypass CloudFormation and create drift on purpose; --express reports success before resources stabilize and disables automatic rollback. You MUST NOT use either in production. A failed --express deployment cannot be rolled back — recover by rolling forward with another --express deploy. See fast-deployments.
Non-empty S3 buckets persist after destroy: You MUST set both removalPolicy: DESTROY and autoDeleteObjects: true. Versioned buckets are worse — delete markers persist even after apparent deletion.
| Task | Quick Command | Details |
|---|---|---|
| Bootstrap | cdk bootstrap aws://$ACCOUNT/$REGION |
bootstrap-and-project-setup |
| New TS project | cdk init app --language typescript — use tsx, eslint-plugin-awscdk |
bootstrap-and-project-setup |
| New Python project | cdk init app --language python — pin deps, use virtualenv |
bootstrap-and-project-setup |
| Deploy | cdk synth --strict → cdk diff → cdk deploy |
Always diff before deploy to production |
| Fast dev iteration | cdk deploy --hotswap-fallback, cdk watch, or cdk deploy --express — dev only, never production |
fast-deployments |
| cdk-nag | Aspects.of(app).add(new AwsSolutionsChecks()) |
compliance-and-drift |
| Drift | cdk drift $STACK (use --fail in CI) |
compliance-and-drift |
| Import resource | cdk import (interactive or --resource-mapping for CI), cdk deploy --import-existing-resources |
import-and-migrate |
| Refactor safely | cdk refactor --unstable=refactor — no property changes in same deploy |
refactor-and-prevent-replacement |
Both trade safety for speed and you MUST NOT use either in production.
Choosing between them: Use --hotswap / --hotswap-fallback for the fastest loop when you work mostly with hotswappable resources and drift does not matter. Use --express when drift is unacceptable, or your resources are not hotswappable.
Recovery workflows (hotswap drift via --revert-drift, rolling a failed --express deploy forward), the hotswappable-resource rules, and IAM/monitoring enforcement of the prod prohibition are all in the full guide: fast-deployments.
| Error | Cause → Fix |
|---|---|
| DeployFailed / DeploymentError | CDK error isn't the root cause. cdk deploy $STACK --verbose, then cdk --unstable=diagnose diagnose $STACK (CLI ≥ 2.1120.0); else aws cloudformation describe-events --stack-name $STACK --filters FailedEvents=true — the first _FAILED event is the cause. Details |
| NoCredentials / ExpiredToken / AssumeRoleFailed | aws sts get-caller-identity + cdk doctor. Expired SSO, missing env, missing sts:AssumeRole. Details |
| Asset errors (CannotFindAsset, FailedToBundleAsset, AssetBuildFailed, AssetPublishFailed) | Path wrong, Docker not running, or bootstrap bucket perms. Use path.join(__dirname, ...). Details |
| AppRequired | Add "app": "npx tsx bin/my-app.ts" to cdk.json. Details |
| AnnotationErrors | Fix the underlying issue; suppress with NagSuppressions only as last resort. Details |
| ConcurrentReadLock / ConcurrentWriteLock | rm -rf cdk.out then re-run. Parallel CI: --output ./cdk.out.$BUILD_ID. Details |
| BootstrapVersionValidation | Re-bootstrap. Match --qualifier everywhere. Details |
| DependencyCycle | Extract shared resource into third stack or use SSM for late-binding. Details |
| UnresolvedAccount | Set explicit env: { account, region } on stack. Commit cdk.context.json. Details |
| NoStacksMatched | CDK uses logical ID (2nd constructor arg), not CFN name. cdk list to find IDs. Details |
| Cannot find module (synth time) | Run npx tsc --noEmit, check cdk.json app path matches tsconfig.json outDir, delete stale .js files. Python: activate venv. Details |
| V1 import paths / duplicate aws-cdk-lib | V1 @aws-cdk/* imports, wrong Construct import, duplicate lib copies in monorepos. Details |
| Lambda Cannot find module (runtime) | Wrong handler value, missing AWS SDK v3 migration, Python deps not bundled. Details |
| API Gateway multi-stage conflicts | Set deploy: false on RestApi, create Deployment and Stage explicitly. Details |
Change didn't deploy under --hotswap |
Changes to non-hotswappable resources are silently ignored and only logged — the command still reports success. Read the output; use --hotswap-fallback to force a CloudFormation deployment instead. Details |
Failed --express deploy / can't roll back |
Express mode cannot use the Rollback Stack API, and a standard deploy MUST NOT be used to recover it. Roll forward: fix the cause, then cdk deploy $STACK --express. Details |
| Unexpected drift on a dev stack | Hotswap and cdk watch create drift by design. Until reverted, the live resources — not CloudFormation's records — are authoritative. Reconcile with cdk deploy $STACK --revert-drift, which uses Drift Aware Changesets to bring live resources in line with the template (updates reality to match desired state; does NOT rewrite CF records to match drifted resources). Details |
Prefer L2. Use L1 with Mixins/Facades when L2 lacks a property. Escape hatches: node.defaultChild → addPropertyOverride. See construct-patterns.
--custom-permissions-boundary on bootstrapgrant*() for inter-resource IAMcdk-nag + --strict in CIterminationProtection: truecdk.context.json原文・著作権は Anthropic および各プラグイン作者に帰属します。日本語訳は Claude API による自動翻訳です。