aws-cdk

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

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.
专注于CDK构造编写、部署工作流、合规性、漂移问题、资源导入、安全重构,以及排查CDK CLI / CloudFormation错误的领域专业知识。
不适用于以下场景: 原生CloudFormation YAML/JSON、SAM、Terraform/Pulumi、超出CDK Pipelines范畴的CI/CD。这些场景请使用内置知识或专门技能。

Critical Warnings

重要警告

Deadly embrace: Removing a cross-stack reference deadlocks deployment. Two-deploy fix required: (1) remove consumer import + add
this.exportValue()
on producer, deploy; (2) remove
exportValue()
, deploy again. 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>
. See troubleshooting-deployment.
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.
致命死锁: 移除跨堆栈引用会导致部署死锁。需要分两次部署修复:(1) 移除消费者的导入,并在生产者端添加
this.exportValue()
,执行部署;(2) 移除
exportValue()
,再次执行部署。详见troubleshooting-deployment
构造ID变更会触发资源替换: 重命名或移动构造会改变其逻辑ID → CloudFormation将替换该资源(有状态资源会丢失数据)。部署前务必执行
cdk diff
。详见refactor-and-prevent-replacement
UPDATE_ROLLBACK_FAILED: 堆栈陷入停滞状态。使用
cdk rollback $STACK
cdk rollback $STACK --orphan <LogicalId>
修复。详见troubleshooting-deployment
非空S3存储桶在销毁后仍会保留: 必须同时设置
removalPolicy: DESTROY
autoDeleteObjects: true
。启用版本控制的存储桶情况更糟——即使看似已删除,删除标记仍会保留。

Common Workflows

常见工作流

TaskQuick CommandDetails
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 prod
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
任务快速命令详情
引导环境
cdk bootstrap aws://$ACCOUNT/$REGION
bootstrap-and-project-setup
创建新TS项目
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
生产环境部署前务必执行diff
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

Troubleshooting

故障排查

ErrorCause → Fix
DeployFailed / DeploymentErrorCDK error is not root cause. Check CFN events:
aws cloudformation describe-stack-events --stack-name $STACK --query "StackEvents[?contains(ResourceStatus,'FAILED')]"
. 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
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 / ConcurrentWriteLock
rm -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 SDK v3 migration, Python deps not bundled. Details
API Gateway multi-stage conflictsSet
deploy: false
on
RestApi
, create
Deployment
and
Stage
explicitly. Details
错误原因→修复
DeployFailed / DeploymentErrorCDK错误并非根本原因。检查CFN事件:
aws cloudformation describe-stack-events --stack-name $STACK --query "StackEvents[?contains(ResourceStatus,'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删除
cdk.out
目录后重新运行。并行CI环境:使用
--output ./cdk.out.$BUILD_ID
指定输出目录。详情
BootstrapVersionValidation重新执行引导操作。确保所有地方的
--qualifier
参数一致。详情
DependencyCycle将共享资源提取到第三个堆栈,或使用SSM进行延迟绑定。详情
UnresolvedAccount在堆栈上显式设置
env: { account, region }
配置。提交
cdk.context.json
文件。详情
NoStacksMatchedCDK使用逻辑ID(构造函数的第二个参数),而非CFN名称。执行
cdk list
查看ID。详情
Cannot find module(合成阶段)执行
npx tsc --noEmit
检查,确保
cdk.json
中的应用路径与
tsconfig.json
outDir
匹配,删除过期的
.js
文件。Python环境:激活虚拟环境。详情
V1 import paths / duplicate aws-cdk-lib使用了V1版本的
@aws-cdk/*
导入、错误的
Construct
导入、单体仓库中存在重复的库副本。详情
Lambda Cannot find module(运行时)处理程序值错误、未完成SDK v3迁移、Python依赖未打包。详情
API Gateway multi-stage conflicts
RestApi
上设置
deploy: false
,显式创建
Deployment
Stage
详情

Construct Patterns

构造模式

Prefer L2. Use L1 with Mixins/Facades when L2 lacks a property. Escape hatches:
node.defaultChild
addPropertyOverride
. See construct-patterns.
优先使用L2构造。当L2缺少所需属性时,结合Mixins/Facades使用L1构造。逃生舱:
node.defaultChild
addPropertyOverride
。详见construct-patterns

Additional Resources

额外资源

  • Search AWS documentation for "CDK Developer Guide", "CDK API Reference" and "CDK Pipelines" respectively
  • 在AWS文档中分别搜索「CDK Developer Guide」「CDK API Reference」和「CDK Pipelines」

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
  • 为CI/CD凭证使用OIDC(无静态密钥)
  • 引导时使用
    --custom-permissions-boundary
    参数
  • 资源间IAM权限使用
    grant*()
    方法
  • CI中使用
    cdk-nag
    +
    --strict
    参数
  • 有状态资源放在单独堆栈中,并设置
    terminationProtection: true
  • 提交
    cdk.context.json
    文件