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://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/import-and-migrate.md
Import and Migrate Reference
Table of Contents
Overview
Read-Only References (from* Methods)
Full Resource Adoption (cdk import)
CI-Friendly Import (--import-existing-resources)
Migrating with cdk migrate
From an Existing Stack
From a Template File
From a Live Account Scan
Migration Constraints
First Deploy After Migration
Incremental Refactoring
Post-Import Verification
Overview
CDK provides three mechanisms for referencing or adopting existing AWS resources, plus a migration tool for converting existing CloudFormation stacks or live infrastructure into CDK code. The right mechanism depends on whether you need read-only access or full lifecycle management.
| Mechanism | Use Case | Lifecycle Control |
|---|---|---|
from* methods | Reference existing resources | Read-only |
cdk import | Adopt resources into a stack | Full (interactive) |
--import-existing-resources | Adopt resources in CI | Full (automated) |
cdk migrate | Convert stacks/infra to CDK code | Full |
Read-Only References (from* Methods)
Use from* static methods (e.g., Bucket.fromBucketName(),
Vpc.fromLookup()) to reference existing resources without managing their
lifecycle:
const bucket = s3.Bucket.fromBucketName(this, 'ImportedBucket', '$BUCKET_NAME');
const vpc = ec2.Vpc.fromLookup(this, 'ImportedVpc', { vpcId: '$VPC_ID' });Constraints:
from*references are read-only — CDK MUST NOT attempt to modify or delete these resources.fromLookupmethods require theenvproperty (account and region) to be set on the stack. They perform API calls at synth time and cache results incdk.context.json.cdk.context.jsonSHOULD be committed to version control so that synth is reproducible without network access.
Full Resource Adoption (cdk import)
cdk import adopts existing resources into a CDK stack so CDK fully manages their lifecycle.
Interactive (default):
cdk import $STACK_NAMEThe CLI prompts for each resource's physical identifier (bucket name, table name, etc.).
Non-interactive (CI-friendly):
# First, generate a mapping template:
cdk import $STACK_NAME --record-resource-mapping mapping.json
# Fill in the physical resource IDs, then import:
cdk import $STACK_NAME --resource-mapping mapping.jsonWorkflow:
Add the construct to your CDK code matching the existing resource's properties
Run
cdk import $STACK_NAME(interactive) or with--resource-mapping(CI)CloudFormation executes an import change set — no resource is created
Constraints:
Not all CloudFormation resource types support import
Resources that depend on each other MUST be imported together or in the correct order
The only allowed changes during import are additions of the imported resources
CI-Friendly Import (--import-existing-resources)
For non-interactive, CI-friendly imports, use the --import-existing-resources flag during a normal deploy:
cdk deploy $STACK_NAME --import-existing-resourcesThe CLI matches resources in the synthesized template against existing unmanaged resources in the account by their custom physical name (e.g., explicit bucketName, tableName, roleName). Matches are imported instead of created.
Constraints:
You MUST set explicit physical names on resources you want to import — auto-generated names cannot be matched
The resource MUST be unmanaged (not already part of another CloudFormation stack)
Not every resource type supports CloudFormation import
Supports mixed operations — you can add new resources AND import existing ones in the same deploy
When to prefer over cdk import:
CI/CD pipelines where interactive prompts are not possible
Rolling out a new stack that overlaps with existing resources
Mixed operations (new + imported resources in one change set)
Migrating with cdk migrate
cdk migrate generates CDK code from existing CloudFormation stacks, template
files, or live account scans.
From an Existing Stack
cdk migrate --from-stack --stack-name $STACK_NAMEFrom a Template File
cdk migrate --from-path $TEMPLATE_FILE_PATH --stack-name $STACK_NAMEFrom a Live Account Scan
cdk migrate --from-scan --stack-name $STACK_NAMEMigration Constraints
Output is L1 constructs only (
Cfn*classes). Higher-level L2/L3 constructs are NOT generated.Only a single stack can be migrated per invocation.
Assets are not migrated — inline code, S3 references, and Docker images MUST be handled manually after migration.
First Deploy After Migration
A migrate.json file is generated alongside the CDK code. This file is
REQUIRED for the first deployment after migration — it tells CloudFormation to
import the existing resources rather than creating new ones.
cdk deploy $STACK_NAMEThe migrate.json file is consumed automatically on the first deploy and MAY
be removed afterward.
Incremental Refactoring
After migration, incrementally refactor L1 constructs to L2/L3 constructs:
Replace one
Cfn*resource at a time with its L2/L3 equivalent.Run
cdk diffafter each change to verify no unintended replacements.Deploy incrementally to validate each refactoring step.
Post-Import Verification
After importing or migrating resources, the following steps MUST be performed:
Verify drift — Run
cdk drift $STACK_NAMEto confirm the imported resource state matches the CDK definition.Protect logical IDs — Logical ID changes after import will cause resource replacement. Lock logical IDs with unit tests or use
overrideLogicalId()where necessary.Run
cdk diff— Confirm no unexpected changes are pending before the next deployment.
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 or AWS.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download aws-cdk.zip