aws-cdk

작성자: aws

CDK를 TypeScript 또는 Python과 함께 사용하여 AWS 인프라를 작성, 배포, 문제 해결합니다. 모범 사례, 스택 아키텍처, 구성 패턴을 다룹니다.…

npx skills add https://github.com/aws/agent-toolkit-for-aws --skill aws-cdk

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

aws의 다른 스킬

analyzing-release-readiness
aws
GitHub PR, GitLab MR 또는 로컬 브랜치에서 병합 전 릴리스 준비 검토를 트리거합니다. 사용자가 코드 변경 사항의 위험성, 정확성 등을 분석하려 할 때 사용합니다.
scanning-with-aws-security-agent
aws
작업 공간에서 AWS Security Agent 스캔 실행 — 소스를 AWS에 업로드하고, 관리형 Security Agent 서비스로 스캔한 후, 순위가 매겨진 검증된 결과를 반환합니다…
coordinating-multi-space-devops-agent
aws
하나의 Claude Code 세션에서 여러 AgentSpaces에 걸쳐 AWS DevOps Agent를 조정하세요 — 질문을 올바른 공간(프로덕션 vs 스테이징 vs 지식)으로 라우팅하고,…
aws-security
aws
AWS 보안 서비스 및 워크플로우를 다룹니다 — Security Hub V2 (OCSF) findings, 커넥터, 애그리게이터, 자동화 규칙, 보안 상태 요약 등…
querying-aws-sagemaker-catalog
aws
SageMaker Catalog 자산 메타데이터 테이블에서 SQL 분석을 실행하며, S3 Tables에서 Apache Iceberg로 내보낸 데이터를 대상으로 합니다. 거버넌스 쿼리, 자산 성장 추적 등을 다룹니다.
agents-connect
aws
에이전트를 Gateway를 통해 외부 API, 도구 또는 서비스에 연결하거나 Cedar 정책으로 도구 접근을 제한할 때 사용합니다. 게이트웨이 설정, 대상...
aurora-dsql
aws
Aurora DSQL 클러스터를 프로비저닝하고 관리하며, psql 또는 DSQL 커넥터를 통해 연결하고, 스키마를 관리하고, 쿼리를 실행하고, MySQL에서 마이그레이션하고, 쿼리 계획을 진단합니다.
transitgateway
aws
AWS Transit Gateway를 구성합니다: 허브를 생성하고 VPC를 연결하며, 라우팅 테이블로 트래픽을 분리하고, 허브를 통해 이그레스 및 검사를 중앙화합니다…