AWS CDK · Cloud Development Kit

Write infrastructure in TypeScript, Python, Java, C# or Go; the CDK compiles it to a CloudFormation template and deploys that. You get loops, functions, types and IDE autocomplete — plus the ability to ship infrastructure and application code in the same project.

Viết hạ tầng bằng TypeScript, Python, Java, C# hay Go; CDK biên dịch nó thành template CloudFormation rồi deploy. Bạn có vòng lặp, hàm, kiểu dữ liệu và IDE autocomplete — cộng thêm khả năng ship hạ tầng và code ứng dụng trong cùng một project.

Reach for it / not the right toolKhi nào dùng / khi nào không

Reach for CDKChọn CDK

  • The template would need repetition — the same subnet/alarm/queue ×12. A for loop beats 800 lines of YAML.Template sẽ phải lặp lại — cùng subnet/alarm/queue ×12. Một vòng for thắng 800 dòng YAML.
  • You want infrastructure and Lambda/container code in one repo, deployed by one command.Muốn hạ tầng và code Lambda/container trong một repo, deploy bằng một lệnh.
  • Least-privilege IAM without writing policy JSON — table.grantReadData(fn).IAM least-privilege mà không viết policy JSON — table.grantReadData(fn).
  • You want to unit-test infrastructure (assert the synthesised template contains an encrypted bucket).Muốn unit-test hạ tầng (assert template synth ra có bucket đã mã hoá).

Not the right toolKhông phải chỗ dùng

  • The audience is non-developers or a compliance team who must read the template → plain CloudFormation / Service Catalog.Người đọc là không phải dev hoặc team tuân thủ phải đọc template → CloudFormation thuần / Service Catalog.
  • A small purely serverless app where you also want sam local → SAM is less machinery.App thuần serverless nhỏ và muốn có sam local → SAM nhẹ máy móc hơn.
  • You need exactly reproducible templates reviewed line-by-line — a CDK library upgrade can change the synthesised output.Cần template tái lập chính xác và review từng dòng — nâng cấp thư viện CDK có thể đổi đầu ra synth.

The pipeline from code to resourcesĐường đi từ code tới resource

A CDK application written in TypeScript, Python, Java, C# or Go contains constructs for Lambda, DynamoDB, S3, API Gateway and ECS. The CDK CLI synthesises it into a CloudFormation template plus assets uploaded to the bootstrap S3 bucket and ECR repository, and CloudFormation then creates the real resources. CDK application Lambda DynamoDB S3 API Gateway ECS · EKS · VPC · alarms TS · Python · Java · C# · Go CDK CLI cdk synth CFN template cdk.out/ Assets S3 · ECR (bootstrap) CloudFormation cdk deploy = synth + upload assets + create/update the stack

Nothing about CDK survives into the running account — CloudFormation owns the resources. That means drift detection, change sets and DeletionPolicy all still apply, and someone can inspect the stack without knowing CDK exists.

Không có gì của CDK còn lại trong account đang chạy — CloudFormation sở hữu resource. Nghĩa là drift detection, change set và DeletionPolicy vẫn áp dụng, và người khác xem stack được mà không cần biết CDK tồn tại.

Construct levels — the thing to actually understandCấp construct — thứ thực sự cần hiểu

A construct is a reusable object that represents one or more resources. The level tells you how much CDK is doing for you. Một construct là object tái sử dụng đại diện cho một hoặc nhiều resource. Cấp độ cho biết CDK làm hộ bạn bao nhiêu.

LevelCấp What you getBạn nhận được gì
L1 — CfnBucket 1:1 with a CloudFormation resource, auto-generated from the CFN spec. Every property required, nothing inferred. Use when a feature is too new for L2.1:1 với resource CloudFormation, sinh tự động từ spec CFN. Phải khai đủ property, không suy diễn gì. Dùng khi tính năng quá mới, chưa có L2.
L2 — s3.Bucket Curated: sensible secure defaults (encryption, block public access), plus helper methods — bucket.grantRead(fn) writes the IAM policy and the KMS grant for you. This is where you live.Được tuyển chọn: mặc định an toàn (mã hoá, chặn public access), kèm method tiện ích — bucket.grantRead(fn) viết hộ cả IAM policy lẫn grant KMS. Đây là chỗ bạn làm việc.
L3 — ApplicationLoadBalancedFargateService Patterns: a whole architecture in one object — VPC wiring, ALB, target group, task definition, service, security groups, log group.Pattern: cả một kiến trúc trong một object — nối VPC, ALB, target group, task definition, service, security group, log group.
The treeCây construct App → one or more Stacks (each = one CloudFormation stack) → Constructs nested arbitrarily deep. Resource logical IDs are derived from the path through this tree — which is why renaming a construct in code replaces the resource on the next deploy. App → một hoặc nhiều Stack (mỗi cái = một CloudFormation stack) → Construct lồng nhau tuỳ ý. Logical ID của resource sinh từ đường đi trong cây này — vì vậy đổi tên construct trong code sẽ tạo lại resource ở lần deploy sau.

What the code looks likeCode trông như thế nào

A public, load-balanced Fargate service — VPC, cluster, ALB, target group, task definition and security groups — in about fifteen lines. Một Fargate service public có load balancer — VPC, cluster, ALB, target group, task definition và security group — trong khoảng mười lăm dòng.

export class MyEcsStack extends Stack {
  constructor(scope: App, id: string, props?: StackProps) {
    super(scope, id, props);

    const vpc = new ec2.Vpc(this, 'MyVpc', { maxAzs: 3 });        // L2 → subnets,
                                                                  // route tables, NAT, IGW
    const cluster = new ecs.Cluster(this, 'MyCluster', { vpc });

    // L3 pattern: ALB + target group + task definition + service + SGs
    new ecs_patterns.ApplicationLoadBalancedFargateService(this, 'MySvc', {
      cluster,
      cpu: 512,                    // default 256
      desiredCount: 6,             // default 1
      memoryLimitMiB: 2048,        // default 512
      publicLoadBalancer: true,    // default false
      taskImageOptions: { image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample') },
    });
  }
}
# the IAM story — no policy JSON anywhere
table = dynamodb.Table(self, "Orders", partition_key=..., encryption=...)
fn    = _lambda.Function(self, "Handler",
            runtime=_lambda.Runtime.PYTHON_3_12,
            handler="app.handler",
            code=_lambda.Code.from_asset("src/handler"))   # ← folder uploaded as an asset

table.grant_read_write_data(fn)        # least-privilege policy generated for you
fn.add_environment("TABLE_NAME", table.table_name)

Bootstrap — the step everyone forgetsBootstrap — bước ai cũng quên

  • cdk bootstrap aws://ACCOUNT/REGION deploys a stack named CDKToolkit containing an S3 bucket (templates + zipped Lambda code), an ECR repo (Docker images) and IAM roles the CLI assumes. cdk bootstrap aws://ACCOUNT/REGION deploy một stack tên CDKToolkit gồm một bucket S3 (template + code Lambda zip), một repo ECR (Docker image) và các IAM role mà CLI assume.
  • Once per account and region. A multi-region deploy needs bootstrapping in each region; cross-account pipelines need --trust so the pipeline account can deploy into the target. Một lần cho mỗi account và mỗi region. Deploy đa region phải bootstrap từng region; pipeline cross-account cần --trust để account pipeline deploy được vào account đích.
  • Symptom of forgetting: "This stack uses assets, so the toolkit stack must be deployed to the environment". Triệu chứng khi quên: "This stack uses assets, so the toolkit stack must be deployed to the environment".
  • The bootstrap roles are powerful by default (AdministratorAccess on the CFN execution role). In a regulated account, bootstrap with --cloudformation-execution-policies scoped down. Role bootstrap mặc định rất mạnh (AdministratorAccess trên CFN execution role). Trong account bị quản chặt, bootstrap với --cloudformation-execution-policies thu hẹp lại.

The CLI worth rememberingNhững lệnh CLI đáng nhớ

cdk synth emit the CloudFormation template to cdk.out/ — deploys nothingxuất template CloudFormation ra cdk.out/ — không deploy gì
cdk diff compare synthesised vs deployed — the CDK equivalent of a change setso bản synth với bản đã deploy — tương đương change set
cdk deploy upload assets, create/update the stack; prompts on IAM/SG changesupload asset, tạo/update stack; hỏi lại khi đổi IAM/SG
cdk deploy --hotswap skip CFN and patch Lambda/ECS directly — dev only, causes driftbỏ qua CFN, vá thẳng Lambda/ECS — chỉ dev, gây drift
cdk destroy delete the stack (same DeletionPolicy rules apply)xoá stack (vẫn theo luật DeletionPolicy)
cdk import · cdk migrate adopt existing resources · turn an existing template/account into CDK codenhận resource có sẵn · biến template/account có sẵn thành code CDK
CDK + SAM CLICDK + SAM CLI CDK has no local runtime of its own, but the two compose: cdk synth --no-staging writes a template to cdk.out/, then sam local invoke MyFunction -t ./cdk.out/MyStack.template.json runs it in Docker. Best of both — CDK to author, SAM to test locally. CDK không có runtime cục bộ riêng, nhưng hai bên ghép được: cdk synth --no-staging ghi template ra cdk.out/, rồi sam local invoke MyFunction -t ./cdk.out/MyStack.template.json chạy nó trong Docker. Được cả hai — CDK để viết, SAM để test cục bộ.

Choosing between the threeChọn giữa ba cái

CloudFormation SAM CDK
You writeBạn viết YAML / JSON YAML (shorthand)YAML (viết tắt) TS · Python · Java · C# · Go
ScopePhạm vi every AWS resourcemọi resource AWS serverless shorthand (+ raw CFN)viết tắt cho serverless (+ CFN thô) every AWS resourcemọi resource AWS
Local testingTest cục bộ — sam local via SAM CLI on cdk.outqua SAM CLI trên cdk.out
Loops / conditionalsVòng lặp / điều kiện Conditions, Fn::ForEach same as CFNnhư CFN the language's owncủa chính ngôn ngữ
Ships app codeShip kèm code app you upload to S3 yourselfbạn tự upload lên S3 sam build/package assets (code and Docker images)asset (code và Docker image)
Runs asChạy dưới dạng — a CloudFormation stack, in all three cases —— một CloudFormation stack, cả ba trường hợp —

Exam reflexesPhản xạ khi thi

The question says…Đề nói… AnswerTrả lời
"Define infrastructure in a familiar programming language""Định nghĩa hạ tầng bằng ngôn ngữ lập trình quen thuộc" CDK
"Deploy infrastructure and application runtime code together""Deploy hạ tầng và code runtime cùng lúc" CDK (assets)(asset)
"Developers keep mis-configuring S3 buckets in templates""Dev cứ cấu hình sai S3 bucket trong template" CDK L2 constructs (secure defaults) or a shared L3 construct libraryCDK L2 construct (mặc định an toàn) hoặc thư viện L3 dùng chung
"First deploy into a new region fails with a toolkit error""Deploy lần đầu vào region mới lỗi toolkit" Run cdk bootstrap in that regionChạy cdk bootstrap ở region đó
"Preview changes before deploying""Xem trước thay đổi trước khi deploy" cdk diff (→ a CloudFormation change set)(→ change set CloudFormation)
"Only Lambda + API Gateway, and we need local testing""Chỉ Lambda + API Gateway, và cần test cục bộ" SAM