Ravindra BagaleCourses & study guides मराठी Track your progress

AWS Cloud

What Is AWS CDK? Cloud Development Kit in TypeScript and Python Explained

CloudFormation YAML is like writing a novel in pure HTML. AWS CDK lets you write TypeScript or Python that *generates* that CloudFormation — loops, types, and your editor help you, then synth emits the template.

In this chapter

  • Why CDK exists beside raw CloudFormation
  • App, Stack, Construct levels
  • cdk synth, diff, deploy, destroy
  • CDK vs Terraform vs raw YAML
  • Lab, errors, FAQ, interview

1. Everyday example first

A Mumbai team copied 800-line YAML for every microservice. One parameter typo broke prod. CDK constructs gave them a typed Factory for "API + Lambda + alarm".

AWS CDK (Cloud Development Kit) is a framework: you write constructs in TypeScript, Python, Java, Go or C#. cdk synth emits CloudFormation; cdk deploy ships it. L2 constructs add sane defaults; L3 patterns bundle architectures.

CDK pathWrite constructscdk synthCloudFormation templatecdk deploy → AWS
You still need CloudFormation skills to read diffs.

2. App, Stack, Construct

Think of one CDK app for the college’s document upload service. A construct is a building block in its code. A bucket construct represents the bucket, and a pattern construct can include several related resources. A stack groups the resources that CloudFormation will deploy together. The app can contain a test stack and a production stack. Follow the bucket in code to the resource type AWS::S3::Bucket in the generated template, then to the deployed bucket after a successful change.

LevelMeaningExample
AppRoot; holds stacksbin/app.ts
StackOne deployable CFN unitStagingApiStack
Construct L11:1 CFN resourceCfnBucket
Construct L2Curated helpers3.Bucket
Construct L3Pattern / kitapi-gateway + lambda kit
# Python sketch
from aws_cdk import App, Stack, RemovalPolicy
from aws_cdk import aws_s3 as s3

class LogsStack(Stack):
    def __init__(self, scope, id, **kw):
        super().__init__(scope, id, **kw)
        s3.Bucket(self, "Logs",
                  versioned=True,
                  removal_policy=RemovalPolicy.DESTROY,
                  auto_delete_objects=True)

app = App()
LogsStack(app, "LabLogsStack")
app.synth()

3. CDK vs Terraform vs YAML

CDK code runs during synthesis to build the CloudFormation template. CloudFormation then handles creating or updating the deployed resources. Read the generated output before deploying so you can answer which resource the code asks AWS to create and which settings it gives that resource. A reusable construct lets you share good settings for the next stack. That brings consistency only if its generated resource properties are the ones you intended.

  • Raw YAML/JSON: universal, verbose, weak editor help.
  • CDK: best when your team already ships TypeScript/Python and lives on AWS.
  • Terraform: strong multi-cloud and existing module culture.
  • Many orgs use CDK inside AWS accounts and Terraform at the org edge — both fine.

Ravindra Bagale's Tip

Read every cdk diff like a production change ticket. Synth is not deploy.

4. Industries

  • Product startups: L3 patterns for each microservice.
  • Enterprises: CDK Pipelines + CodePipeline for git-driven deploys.
  • Data platforms: typed Glue/S3/Lake constructs.
  • Security teams: constructs that force KMS + logging.
  • Agencies: publish private construct libraries per client baseline.

5. Mini lab: bucket stack

Start by synthesising the lab stack and find the single bucket resource in the generated template. Read its versioning and removal behavior. If you change the bucket property, repeat synthesis and review the difference. In a sandbox deployment, verify the stack status and the actual bucket setting. During cleanup, confirm which resources belonged to your lab stack and keep any shared bootstrap assets.

Do this in ap-south-1 (Mumbai) unless your org forbids it. Set a budget alert first.

  1. Install Node LTS + aws-cdk CLI; aws configure sandbox.
  2. cdk init app --language typescript (or python).
  3. Add an s3.Bucket with removal_policy DESTROY for lab.
  4. cdk synth && cdk diff && cdk deploy.
  5. Open CloudFormation console; find the nested template resources.

Cleanup (stop billing)

  1. cdk destroy — confirm bucket empty/auto-delete.
  2. Delete leftover CDKToolkit bootstrap stack only if your org allows and nothing else uses it.

6. Common errors and fixes

Each row is a real mistake students and juniors hit. Read the fix before you panic.

Error / symptomFix
Need to perform AWS calls / bootstrapRun cdk bootstrap in the account/region once.
Checksum / asset failuresClean cdk.out; check Docker if bundling Lambdas.
Hotswap false confidenceHotswap skips full CFN — not for prod IAM changes.
Stack stuck DELETE_FAILEDEmpty S3/non-empty buckets; set auto_delete or empty manually.
Context growing hugePrune cdk.context.json carefully in teams.
Circular dependencySplit stacks or use lazy values / exports wisely.
Wrong account from SSOCheck aws sts get-caller-identity before deploy.
IAM too open in L2 defaultsReview generated policies; tighten.
Python venv missing cdk libspip install -r requirements.txt inside venv.
Diff looks empty but expect changeYou edited wrong stack id / env.

7. Troubleshooting checklist

  1. aws sts get-caller-identity
  2. cdk doctor
  3. rm -rf cdk.out && cdk synth
  4. Read CloudFormation events for the failed resource.
  5. Compare with a minimal empty stack deploy.

8. FAQ

Q. Does CDK replace CloudFormation?

No — it generates and deploys it.

Q. TypeScript or Python?

Pick the language your team already reviews in PRs.

Q. Can I escape to raw CFN?

Yes — L1 Cfn* resources and escapes.

Q. Is cdk deploy recursive for all stacks?

You choose stacks; use stages in pipelines for order.

Q. Unit testing?

assertions module / template hasResource — test synth output.

9. Interview Q&A

Q. What is a construct?

A reusable building block that emits one or more CFN resources.

Q. synth vs deploy?

synth only writes templates; deploy applies them to AWS.

Q. L1 vs L2?

L1 maps 1:1 to CFN; L2 adds defaults and helper methods.

Q. Why bootstrap?

Account/region needs CDK toolkit assets bucket and roles.

Q. CDK vs Terraform?

CDK = AWS-first code in familiar languages; TF = HCL multi-cloud.

Q. How to avoid snowflake stacks?

Shared construct libraries + pipelines.

10. Tips in English, Marathi and Hindi

Ravindra Bagale's Tip (EN)

If you cannot read the synth diff, you cannot own the outage.

Ravindra Bagale's Tip (MR)

synth diff वाचता येत नसेल तर outage own करता येणार नाही.

Tip (HI)

synth diff नहीं पढ़ सकते तो outage की ज़िम्मेदारी नहीं ले सकते।

Try at home

  1. Init a CDK app and deploy one bucket to sandbox.
  2. Open cdk.out and find the generated template.
  3. List three YAML stanzas you would wrap as L3.

In short

  1. CDK writes CloudFormation using real programming languages.
  2. App → Stack → Constructs; synth then deploy.
  3. Bootstrap once per account/region.
  4. Review diffs; destroy lab stacks.

Revision, interview and comparison cards

Revise this lesson in a few minutes. Save the cards on your phone or download them as PNG files. The QR code on each card opens this lesson.

Revision card: What is AWS CDK?. Teams who already write TypeScript/Python want infra in the same language, with loops and tests. CDK is a framework: you write app code that synthesizes CloudFormation templates, then deploy the stack. npm/pip install aws-cdk → cdk init → write Stack → cdk synth → cdk deploy. synth emits cdk.out templates; deploy creates a Lambda and API you can curl.
Revision card: What is AWS CDK? · Download PNG · Open card page
Revision card: Constructs L1 / L2 / L3. Using only raw CloudFormation properties in CDK loses the safety of higher constructs. L1 = CFN resources (Cfn*). L2 = opinionated helpers (Bucket, Function). L3 = patterns (whole apps). Prefer L2 Bucket/Function for labs; drop to L1 only for new flags L2 lacks. new lambda.Function(...) sets runtime and code without hand-writing every CFN key.
Revision card: Constructs L1 / L2 / L3 · Download PNG · Open card page
Revision card: cdk diff before deploy. Deploy without diff can replace a table or change a name you did not intend. cdk diff compares local synth to the deployed stack, like terraform plan for CDK. Always diff in CI and on prod stacks; abort if you see Resource replacement on data stores. Diff shows IAM policy widen; you tighten before deploy.
Revision card: cdk diff before deploy · Download PNG · Open card page
Revision card: Hotswap vs full deploy. Waiting for a full CloudFormation deploy on every Lambda code tweak slows class labs. cdk deploy --hotswap can push Lambda code/asset changes faster, skipping some CFN waits (not for all changes). Use hotswap in lab iterations; use full deploy for IAM, VPC, and production releases. Code-only change updates the function in seconds; role change still needs full deploy.
Revision card: Hotswap vs full deploy · Download PNG · Open card page
Revision card: CDK vs Terraform. Picking both tools for the same stack without a rule creates double state and pain. CDK: AWS-first, language + constructs, CFN state. Terraform: multi-cloud HCL, its own state, huge provider ecosystem. Choose one IaC tool per stack. Prefer the one your team already reviews in PRs. A greenfield AWS-only TypeScript team often picks CDK; a multi-cloud shop often picks Terraform.
Revision card: CDK vs Terraform · Download PNG · Open card page
Comparison: AWS CDK vs Raw CloudFormation. AWS CDK: TypeScript/Python constructs that synth to CFN. Raw CloudFormation: Hand-written YAML/JSON templates.
Comparison: AWS CDK vs Raw CloudFormation · Download PNG · Open card page
Comparison: L2 construct vs L1 (Cfn*) construct. L2 construct: Opinionated helpers with safe defaults. L1 (Cfn*) construct: 1:1 CloudFormation resources, every property.
Comparison: L2 construct vs L1 (Cfn*) construct · Download PNG · Open card page
Interview card: What problem does CDK solve?. CDK lets you define AWS infra in TypeScript/Python with constructs, then ships CloudFormation. You get loops, tests, and reuse that raw YAML struggles with. A Function + ApiGateway pattern in one Stack is a typical CDK lab.
Interview card: What problem does CDK solve? · Download PNG · Open card page
Interview card: synth vs deploy?. synth only writes CloudFormation to cdk.out. deploy applies it to the account/region. Always synth/diff in CI before deploy permissions are used. Broken TypeScript fails at synth before any AWS change.
Interview card: synth vs deploy? · Download PNG · Open card page
Interview card: When do you drop to L1?. When L2 lacks a new CloudFormation property you must set. Prefer L2; escape to L1 or aspects carefully and document why. A brand-new Lambda field might need CfnFunction until L2 catches up.
Interview card: When do you drop to L1? · Download PNG · Open card page
Interview card: How do you test CDK?. Use assertions on the synthesized template (fine-grained + snapshot) in unit tests. Fail CI if a public S3 bucket appears in the template. expect(stack).toHaveResource("AWS::S3::Bucket", { PublicAccessBlockConfiguration: ... }).
Interview card: How do you test CDK? · Download PNG · Open card page

More cards: Ravi Sir's Cards.

Practise this chapter

Interview questions and answers

How do you show that a line in a CDK app really changes an AWS property?

Synthesize the stack and find the corresponding CloudFormation resource and property. Review the difference and, in the sandbox, compare the actual deployed setting afterward. The construct code describes behavior and CloudFormation applies the generated infrastructure definitions.

Check your understanding

Choose an answer, then compare your reasoning with the explanation.

0 of 3 answered correctly
1. What is the relationship between a CDK construct and a stack?

Answer and explanation

A. A construct is a building block that can be included in a stack

A CDK stack groups resources for CloudFormation. Constructs describe individual resources or groups and patterns.

2. What does cdk synth produce for the lab stack?

Answer and explanation

B. A CloudFormation template and assembly outputs

Synthesis translates CDK app code into deployable definitions. Deployment is a separate stage.

3. What check is useful before deleting a lab stack that used bootstrapping?

Answer and explanation

A. Separate the disposable stack resources from shared bootstrap resources

Bootstrapping supports deploying to the environment. The lab stack has its own separate lifecycle.

Practice Tasks

Practice checks run in your browser. They check the answer for this exercise; they do not create resources or connect to your AWS account.

About this scenario

Amravati Agro Market is a agriculture business in Amravati. Anjali Thakre looks after its IT and cloud work. They count money in INR and run their AWS resources in the ap-south-1 Region. In the tasks below you do real jobs for them using what this lesson teaches. All names, account IDs, IP addresses and numbers are made up for practice.

0 / 16

Easy cdk.json app entry

CDK needs an app command.

cdk.json with app npx ts-node bin/app.ts.

  1. Start from the top-level keys the task names.
  2. Indent child keys with 2 spaces (no tabs).
  3. Fill in each property with the value from the task.
  4. Click Check answer. Key order does not matter.

Easy List CloudFormation stacks

CDK synthesizes to CFN.

List CloudFormation stacks in ap-south-1.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Easy Describe a stack

See outputs after cdk deploy.

Describe stack amravatiagro-AppStack.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Easy Delete a stack

Tear down lab stacks.

Delete stack amravatiagro-AppStack.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Easy List buckets CDK created

Verify Bucket construct.

List all S3 buckets.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Easy CDK bootstrap stack count typical

cdk bootstrap creates CDKToolkit.

How many primary bootstrap stacks named CDKToolkit does a region usually get?

  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Easy CDK v2 major version number

Modern apps use v2.

What major version number is AWS CDK v2?

  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Medium cdk.context.json AZ list

Context caches lookups.

JSON with availability-zones key mapping ap-south-1 to [ap-south-1a, ap-south-1b].

  1. Start from the top-level keys the task names.
  2. Indent child keys with 2 spaces (no tabs).
  3. Fill in each property with the value from the task.
  4. Click Check answer. Key order does not matter.

Medium Stack events

Debug failed deploys.

Describe stack events for amravatiagro-AppStack.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Medium List stack resources

Map constructs to physical ids.

List stack resources for amravatiagro-AppStack.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Medium Pipeline stages example

Dev then Prod is two.

If a pipeline deploys Dev then Prod, how many app stages is that?

  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Medium CloudFormation Outputs snippet

Expose bucket name.

JSON Outputs with BucketName Value Ref DataBucket.

  1. Start from the top-level keys the task names.
  2. Indent child keys with 2 spaces (no tabs).
  3. Fill in each property with the value from the task.
  4. Click Check answer. Key order does not matter.

Medium Stack tag Project

Tags flow to resources.

JSON Tags array one Key Project Value learn.

  1. Start from the top-level keys the task names.
  2. Indent child keys with 2 spaces (no tabs).
  3. Fill in each property with the value from the task.
  4. Click Check answer. Key order does not matter.

Medium Get a role

CDK creates roles too.

Get IAM role amravatiagro-AppRole.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Medium Get Lambda function config

Function construct maps here.

Get function configuration for amravatiagro-api.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Hard Allow CFN to manage S3

Deployment role needs rights.

Allow s3:CreateBucket and s3:DeleteBucket on arn:aws:s3:::amravatiagro-* .

  1. Start with { "Version": "2012-10-17", "Statement": [ ... ] }.
  2. In each statement write Effect, Action and Resource.
  3. Give only what the task needs (least privilege).
  4. Use double quotes and commas correctly. Click Check answer.