AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides comprehensive support for the AWS CDK, covering the full lifecycle of infrastructure-as-code development. It includes best practices for construct patterns, environment bootstrapping, compliance enforcement, drift detection, and safe refactoring. The skill also offers detailed troubleshooting workflows for common CLI, CloudFormation, and deployment errors, ensuring developers can maintain stable and secure AWS environments using TypeScript or Python.
What it does
- Guides the authoring of AWS infrastructure using L1 and L2 CDK constructs.
- Provides procedures for bootstrapping AWS accounts and regions for CDK usage.
- Enforces security and compliance policies using cdk-nag integration.
- Detects and resolves configuration drift between live resources and CDK templates.
- Offers systematic troubleshooting for deployment failures and asset management issues.
- Details safe refactoring patterns to prevent accidental resource replacement.
When to use it
- When initializing new AWS infrastructure projects in TypeScript or Python.
- When planning complex stack architectures or managing cross-stack references.
- When diagnosing deployment errors or stuck CloudFormation stacks.
- When integrating security compliance checks into the CI/CD pipeline.
- When importing existing AWS resources into a CDK-managed stack.
- When refactoring existing infrastructure without causing data loss or resource replacement.
Advantages
- Reduces risk of accidental resource replacement during stack refactoring.
- Ensures infrastructure compliance through automated policy enforcement.
- Provides clear, actionable steps for resolving complex deployment deadlocks.
- Standardizes project structure and dependency management for CDK apps.
- Offers safe, documented patterns for handling stateful resources and S3 buckets.
Usage examples
- “How do I safely remove a cross-stack reference without breaking my deployment?”
- The agent explains the three-deploy process: weakening the reference strength to WEAK before final removal to avoid the deadly embrace deadlock.
- “My stack is stuck in UPDATE_ROLLBACK_FAILED. How do I fix it?”
- The agent provides commands to use cdk rollback or cdk rollback --orphan to recover the stack state.
- “How can I ensure my CDK app follows AWS best practices?”
- The agent instructs on installing and applying cdk-nag rule packs like AwsSolutionsChecks as an Aspect to the application.
- “I need to import an existing S3 bucket into my CDK stack. What is the process?”
- The agent outlines the cdk import workflow and the necessary steps to align the existing resource with the CDK template.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/aws/aws-cdk/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip aws-cdk.zip -d .agents/skills
Documentation by AWS
AWS CDK
Overview
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.
Critical Warnings
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.
Common Workflows
| 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 |
Fast Deployments — Hotswap vs Express (dev only)
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.
Troubleshooting
| 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 |
Construct Patterns
Prefer L2. Use L1 with Mixins/Facades when L2 lacks a property. Escape hatches: node.defaultChild → addPropertyOverride. See construct-patterns.
Additional Resources
Search AWS documentation for "CDK Developer Guide", "CDK API Reference" and "CDK Pipelines" respectively
Security Considerations
OIDC for CI/CD credentials (no static keys)
--custom-permissions-boundaryon bootstrapgrant*()for inter-resource IAMcdk-nag+--strictin CIStateful resources in own stack with
terminationProtection: trueCommit
cdk.context.json
Files
- ATTRIBUTION.mdAdded by AutoGineer879 B
- LICENSELicence file added by AutoGineer9.9 KiB
- NOTICELicence file added by AutoGineer67 B
- SKILL.md8.7 KiB
- references/bootstrap-and-project-setup.md8.0 KiB
- references/compliance-and-drift.md5.2 KiB
- references/construct-patterns.md10.4 KiB
- references/fast-deployments.md13.4 KiB
- references/import-and-migrate.md6.3 KiB
- references/refactor-and-prevent-replacement.md6.2 KiB
- references/troubleshooting-credentials.md5.8 KiB
- references/troubleshooting-deployment.md12.9 KiB
- references/troubleshooting-synth.md8.8 KiB
- references/v1-to-v2-migration.md3.2 KiB
references/troubleshooting-synth.md
Troubleshooting: Synth Failures
Table of Contents
Overview
Cannot Find Module (Synth Time)
Asset Errors
App Required
Annotation Errors
Concurrent Lock
Dependency Cycle
No Stacks Matched
Overview
This reference covers errors that occur during cdk synth — before any CloudFormation deployment begins. These failures prevent the cloud assembly from being produced. Each section maps a specific error class to its root cause and fix.
Cannot Find Module (Synth Time)
cdk synth fails with Cannot find module (TS) or ModuleNotFoundError (Python) before producing a template. The error occurs at synth time, not deploy time.
For
Cannot find module '@aws-cdk/aws-*'(v1→v2 migration) → see v1-to-v2-migration. ForCannot find moduleat Lambda runtime → see troubleshooting-deployment.
TypeScript — diagnostic flow
Step 1: Run npx tsc --noEmit.
tsc fails → problem is in your TS project. Check: missing
npm ci, wrongtsconfig.jsonpaths/rootDir/typeRoots, duplicateaws-cdk-lib(npm ls aws-cdk-lib), stalenode_modules(rm -rf node_modules && npm ci).tsc succeeds → problem is in how CDK runs your app. Go to Step 2.
Step 2: Check how cdk.json runs your app.
The app field in cdk.json determines the execution mode. The failure causes differ:
If cdk.json uses compiled JS (e.g., "app": "node bin/app.js"):
| Cause | Symptom | Fix |
|---|---|---|
outDir mismatch with cdk.json | Cannot find module 'bin/app.js' | Ensure tsconfig.json outDir aligns with the path in cdk.json. If outDir: "dist", then "app": "node dist/bin/app.js" |
Stale compiled .js files | Module existed before but was renamed/deleted in TS | rm -rf cdk.out dist && npm run build && cdk synth |
| Never compiled | .js files don't exist | Run npx tsc or npm run build before cdk synth |
If cdk.json uses direct TS execution (e.g., "app": "npx tsx bin/app.ts"):
| Cause | Symptom | Fix |
|---|---|---|
| Path aliases not resolved by ts-node | Cannot find module 'lib/MyStack' | Switch to tsx ("app": "npx tsx bin/my-app.ts"), or register tsconfig-paths with ts-node ("app": "npx ts-node -r tsconfig-paths/register --prefer-ts-exts bin/my-app.ts") |
Monorepo — wrong node_modules | Cannot find module 'typescript' | Verify hoisting: npm ls typescript. Point cdk.json at correct binary. pnpm: shamefully-hoist=true. |
npm link / symlinked packages | Cannot find module '@my/shared-constructs' | Install peer deps explicitly, or NODE_OPTIONS=--preserve-symlinks. Long-term: publish to registry. |
| Wrong working directory | cdk.json not found | cd to directory containing cdk.json |
Python — diagnostic flow
Step 1: Check which Python is running — which python vs the interpreter in cdk.json.
Step 2: Test import — python -c "import aws_cdk; print(aws_cdk.__version__)".
| Cause | Symptom | Fix |
|---|---|---|
| Virtualenv not activated | No module named 'aws_cdk' | source .venv/bin/activate && pip install -r requirements.txt |
Missing pip install | No module named 'my_constructs' | pip install -r requirements.txt |
| CI — venv not activated | Module errors in pipeline | Activate in script, or set "app": ".venv/bin/python app.py" in cdk.json |
| Poetry / Pipenv | CDK runs outside managed env | "app": "poetry run python app.py" or "app": "pipenv run python app.py" |
cannot import name 'core' from 'aws_cdk' | v1→v2 API change | Replace from aws_cdk import core with import aws_cdk as cdk. See v1-to-v2-migration. |
Prevention
You SHOULD use
tsxinstead ofts-node— native path alias support, fasterYou SHOULD run
npm ci(TS) orpip install -r requirements.txt(Python) as the first CI stepYou SHOULD install
aws-cdkCLI as a pinned dev dependency and invoke vianpx cdk
Asset Errors
Asset errors occur when CDK cannot locate, bundle, or publish file or Docker image assets.
CannotFindAsset
The asset path does not exist at synth time.
Fix: You MUST use path.join(__dirname, ...) to build asset paths relative to the source file, not the working directory:
new lambda.Function(this, 'Fn', {
code: lambda.Code.fromAsset(path.join(__dirname, '../lambda')),
// ...
});FailedToBundleAsset
The bundling command failed. Common cause: Docker is not running.
Fix: You MUST ensure Docker is running before synth. For Lambda bundling with esbuild, you SHOULD install esbuild locally to avoid the Docker fallback:
npm install --save-dev esbuildAssetBuildFailed
esbuild or Docker build returned a non-zero exit code.
Fix: Run the bundling command manually outside CDK to see the full error output. Check for missing dependencies, syntax errors, or incompatible platform targets.
AssetPublishFailed
The asset was built successfully but upload to the bootstrap S3 bucket or ECR repository failed.
Fix: You MUST verify that the CDK publishing role has permission to write to the bootstrap bucket and ECR repository. Re-bootstrap if necessary:
cdk bootstrap aws://$ACCOUNT/$REGIONApp Required
--app is required either in command-line, in cdk.json, or in ~/.cdk.jsonThe CDK CLI cannot find the app entry point.
Fix: You MUST add the app key to cdk.json:
{
"app": "npx tsx bin/$APP_NAME.ts"
}You SHOULD verify the path points to the file containing your new App() call.
Annotation Errors
An Aspect or construct called Annotations.of(node).addError(), which causes synth to fail. This covers:
cdk-nag errors — security/compliance rule violations.
Custom Aspect errors — organization-wide policy checks.
Built-in CDK warnings promoted to errors by the
--strictflag.
Diagnosis
You MUST fix the underlying issue flagged by the annotation. Read the error message to identify which construct and which rule triggered it.
Suppression (last resort)
You SHOULD only suppress annotations when the flagged pattern is intentional and justified. Suppression patterns for cdk-nag:
Per-resource:
NagSuppressions.addResourceSuppressions(myBucket, [
{ id: '$RULE_ID', reason: '$JUSTIFICATION' },
]);Per-stack:
NagSuppressions.addStackSuppressions(myStack, [
{ id: '$RULE_ID', reason: '$JUSTIFICATION' },
]);By path:
NagSuppressions.addResourceSuppressionsByPath(stack, '/$STACK/$CONSTRUCT_PATH', [
{ id: '$RULE_ID', reason: '$JUSTIFICATION' },
]);You MUST NOT suppress annotations without providing a reason.
Concurrent Lock
Cannot lock cdk.out: file is locked by another processA file lock on the cdk.out directory prevents synth. This happens when a previous synth crashed or when multiple synth processes target the same output directory.
Fix — single build
rm -rf cdk.outFix — parallel CI
You MUST use a unique output directory per build to avoid lock contention:
cdk synth --output ./cdk.out.$BUILD_IDDependency Cycle
Error: 'StackA' depends on 'StackB' depends on 'StackA'A circular reference exists between two or more stacks.
Fixes
Extract shared resource into a third stack. The shared resource lives in its own stack, and both consumers depend on it (one-way).
Use SSM for late-binding. The producer writes a value to SSM Parameter Store; the consumer reads it at deploy time. This breaks the synth-time dependency:
// Producer stack new ssm.StringParameter(this, 'Param', { parameterName: '/$APP/$RESOURCE_ARN', stringValue: resource.resourceArn, }); // Consumer stack const arn = ssm.StringParameter.valueForStringParameter(this, '/$APP/$RESOURCE_ARN');Pass raw ARN strings instead of construct references when the full construct object is not needed.
Prevention
You SHOULD design stack dependencies as one-way: props flow from producer to consumer. You MUST NOT create reverse references from a producer back to its consumer.
No Stacks Matched
No stacks match the name(s) $STACK_NAMECDK selects stacks by their logical ID (the second argument to the Stack constructor), not by the CloudFormation stack name.
Diagnosis
List all stack IDs in the app:
cdk listDeploy options
# Exact logical ID
cdk deploy $STACK_ID
# Wildcard
cdk deploy "$PATTERN*"
# All stacks
cdk deploy --allYou MUST use the logical ID as shown by cdk list, not the CloudFormation stack name visible in the AWS console.
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs Python, Needs Node.js
Security
What our scanner noticed· Medium risk
- References to credential files
- Instructions that use the network
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Published by
- AWS
- Publisher
- AWS (Official)
- Source
- aws/agent-toolkit-for-aws · skills/core-skills/aws-cdk · commit 0a218f8
- Licence
- Apache License 2.0 (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- NOTICE (added by AutoGineer from NOTICE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
- Also distributed in
- aws/agent-toolkit-for-aws
AutoGineer is not affiliated with or endorsed by AWS.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download aws-cdk.zip