Generated banner for AWS Cdk
Generated logo for AWS Cdk

AWS Cdk

AWSOfficialPublished by AWS

  • Skill
  • Tool integration
  • Cloud and DevOps
  • Apache-2.0
  • Medium risk

From the author

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.
— the description by AWS

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

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/aws/aws-cdk/download
  2. Unzip 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

TaskQuick CommandDetails
Bootstrapcdk bootstrap aws://$ACCOUNT/$REGIONbootstrap-and-project-setup
New TS projectcdk init app --language typescript — use tsx, eslint-plugin-awscdkbootstrap-and-project-setup
New Python projectcdk init app --language python — pin deps, use virtualenvbootstrap-and-project-setup
Deploycdk synth --strict → cdk diff → cdk deployAlways diff before deploy to production
Fast dev iterationcdk deploy --hotswap-fallback, cdk watch, or cdk deploy --express — dev only, never productionfast-deployments
cdk-nagAspects.of(app).add(new AwsSolutionsChecks())compliance-and-drift
Driftcdk drift $STACK (use --fail in CI)compliance-and-drift
Import resourcecdk import (interactive or --resource-mapping for CI), cdk deploy --import-existing-resourcesimport-and-migrate
Refactor safelycdk refactor --unstable=refactor — no property changes in same deployrefactor-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

ErrorCause → Fix
DeployFailed / DeploymentErrorCDK 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 / AssumeRoleFailedaws 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
AppRequiredAdd "app": "npx tsx bin/my-app.ts" to cdk.json. Details
AnnotationErrorsFix the underlying issue; suppress with NagSuppressions only as last resort. Details
ConcurrentReadLock / ConcurrentWriteLockrm -rf cdk.out then re-run. Parallel CI: --output ./cdk.out.$BUILD_ID. Details
BootstrapVersionValidationRe-bootstrap. Match --qualifier everywhere. Details
DependencyCycleExtract shared resource into third stack or use SSM for late-binding. Details
UnresolvedAccountSet explicit env: { account, region } on stack. Commit cdk.context.json. Details
NoStacksMatchedCDK 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-libV1 @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 conflictsSet deploy: false on RestApi, create Deployment and Stage explicitly. Details
Change didn't deploy under --hotswapChanges 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 backExpress 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 stackHotswap 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-boundary on bootstrap

  • grant*() for inter-resource IAM

  • cdk-nag + --strict in CI

  • Stateful resources in own stack with terminationProtection: true

  • Commit cdk.context.json

Files

references/bootstrap-and-project-setup.md

Bootstrap and Project Setup Reference

Table of Contents

  • Bootstrap and Project Setup Reference

    • Table of Contents

    • Overview

    • Bootstrap Procedure

      • What Bootstrap Creates

      • Bootstrap Command

      • Cross-Account Trust

      • Custom Qualifier

      • Permissions Boundary

      • Custom Bootstrap Template

      • Bootstrap Constraints

    • TypeScript Project Setup

      • Prerequisites

      • Initialize Project

      • Project Structure

      • Configure tsx

      • Linting

      • Common Commands

    • Python Project Setup

      • Prerequisites

      • Initialize Project

      • Virtual Environment

      • Common Commands

    • Version Management Best Practices

      • CLI and Library Are Separate Release Tracks

      • Feature Flags


Overview

Every CDK deployment target (account + region pair) MUST be bootstrapped before the first deployment. Projects MUST commit a lockfile and SHOULD use strict tooling to ensure reproducible builds.


Bootstrap Procedure

What Bootstrap Creates

The CDKToolkit CloudFormation stack provisions:

  • An S3 bucket (file assets and CloudFormation templates)

  • An ECR repository (Docker image assets)

  • 4 IAM roles for user to assume (deploy, lookup, file-publishing, image-publishing)

  • A CloudFormation execution role

  • An SSM parameter (/cdk-bootstrap/$QUALIFIER/version)

Bootstrap Command
cdk bootstrap aws://$ACCOUNT_ID/$REGION

Bootstrap REQUIRES near-administrator permissions in the target account.

Cross-Account Trust

To allow a CI/CD account to deploy into a target account:

cdk bootstrap aws://$TARGET_ACCOUNT/$REGION \
  --trust $CI_ACCOUNT_ID \
  --cloudformation-execution-policies arn:aws:iam::aws:policy/$POLICY_NAME

The --trust flag grants the specified account permission to assume the CDK roles. The --cloudformation-execution-policies flag MUST be provided with --trust to scope the CloudFormation execution role.

Custom Qualifier

To run multiple independent CDK environments in the same account/region:

cdk bootstrap aws://$ACCOUNT_ID/$REGION --qualifier $QUALIFIER

The qualifier MUST be alphanumeric and at most 10 characters. It distinguishes bootstrap resources from other CDK environments in the same account.

Permissions Boundary

To attach a permissions boundary to all IAM roles created by CDK:

cdk bootstrap aws://$ACCOUNT_ID/$REGION \
  --custom-permissions-boundary $BOUNDARY_POLICY_NAME
Custom Bootstrap Template

To use an organization-approved bootstrap template:

cdk bootstrap aws://$ACCOUNT_ID/$REGION --template $TEMPLATE_PATH
Bootstrap Constraints
  • Deleting the CDKToolkit stack MUST NOT be done — it breaks all deployments in that account/region pair.

  • Termination protection SHOULD be enabled on the CDKToolkit stack.

  • Bootstrap MUST be re-run when upgrading to a CDK version that requires a newer bootstrap stack version.


TypeScript Project Setup

Prerequisites
  • Node.js ≥ 20 MUST be installed.

Initialize Project
cdk init app --language typescript
Project Structure
$PROJECT_ROOT/
├── bin/          # Entry point (App instantiation)
├── lib/          # Stack and construct definitions
├── cdk.json      # CDK configuration
├── package.json
└── tsconfig.json
Configure tsx

The cdk.json app field SHOULD use tsx instead of ts-node for faster startup:

{
  "app": "npx tsx bin/$APP_NAME.ts"
}
Linting

Projects MUST enforce strict typing — any MUST NOT be used. Configure with:

  • eslint + prettier

  • eslint-plugin-awscdk for CDK-specific rules

Construct props interfaces SHOULD use readonly on all properties:

interface MyConstructProps {
  readonly bucketName: string;
  readonly enableVersioning: boolean;
}
Common Commands
cdk synth          # Synthesize CloudFormation template
cdk diff           # Show pending changes
cdk deploy         # Deploy stack(s)
cdk destroy        # Tear down stack(s)
cdk list           # List all stacks in the app

Python Project Setup

Prerequisites
  • Node.js ≥ 20 MUST be installed.

  • Python ≥ 3.9 MUST be installed.

Initialize Project
cdk init app --language python
Virtual Environment

After initialization, activate the virtualenv and install dependencies:

python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt

Dependencies SHOULD be captured in requirements.txt (or poetry.lock / Pipfile.lock) and committed for reproducible builds. See Version Management Best Practices.

Common Commands
cdk synth           # Synthesize CloudFormation template
cdk deploy          # Deploy stack(s)
cdk bootstrap       # Bootstrap target environment
cdk doctor          # Check for potential problems

Version Management Best Practices

  • Commit lockfiles (package-lock.json / poetry.lock / Pipfile.lock). Unlocked builds drift and lose determinism.

  • For CDK applications, use caret (^) ranges for aws-cdk-lib and constructs in dependencies — this is the officially recommended approach. The lockfile provides reproducibility; the caret range lets npm update pull compatible fixes and features.

    {
      "dependencies": {
        "aws-cdk-lib": "^2.170.0",
        "constructs": "^10.5.0"
      }
    }

    Teams that prefer exact pinning for stricter reproducibility SHOULD pair it with automated upgrade tooling (Dependabot, Renovate) to avoid falling behind.

  • For construct libraries, declare aws-cdk-lib and constructs as peerDependencies (caret, widest compatible) and as devDependencies at the oldest supported exact version.

  • Experimental / alpha modules (e.g. @aws-cdk/aws-*-alpha) SHOULD use exact versions — their APIs can change between releases without SemVer guarantees.

  • Automate upgrades: a weekly job that bumps aws-cdk-lib, runs cdk synth to catch breaking changes, deploys to a test environment, and opens a PR on success.

CLI and Library Are Separate Release Tracks

The CDK CLI (aws-cdk) and the library (aws-cdk-lib) are independent packages on different release tracks — their version numbers do NOT align. A CLI at 2.1001.x paired with a library at 2.200.x is normal. The compatibility contract is one-way: a newer CLI can read assemblies produced by older libraries, but an older CLI CANNOT read assemblies produced by newer libraries. The mismatch surfaces as:

This CDK CLI is not compatible with the CDK library used by your application.
(Cloud assembly schema version mismatch)

The fix is to upgrade the CLI to a specific newer version. You MUST install aws-cdk as a dev dependency at an exact version and invoke it via npx cdk; you MUST NOT use aws-cdk@latest anywhere — it is non-deterministic, so a broken release can reach your pipeline instantly.

{
  "devDependencies": {
    "aws-cdk": "2.1010.0"
  }
}
npx cdk synth
npx cdk deploy $STACK_NAME

Bump the pinned CLI version regularly (Dependabot / Renovate), on the same cadence as aws-cdk-lib.

Feature Flags

cdk.json's context object carries CDK feature flags — per-release opt-ins to behaviour changes. When upgrading aws-cdk-lib, review new flags and adopt them incrementally (inspect via cdk flags --unstable=flags). Do not flip everything to recommended in one commit.

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