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

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.

What you'll learn 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

Why do we need this?

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".

What is it?

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

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

  • 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

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

How to do it (step by step)

  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.

Practice Tasks

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

Why: CDK needs an app command.

What to do: cdk.json with app npx ts-node bin/app.ts.

How:
  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

Why: CDK synthesizes to CFN.

What to do: List CloudFormation stacks in ap-south-1.

How:
  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

Why: See outputs after cdk deploy.

What to do: Describe stack amravatiagro-AppStack.

How:
  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

Why: Tear down lab stacks.

What to do: Delete stack amravatiagro-AppStack.

How:
  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

Why: Verify Bucket construct.

What to do: List all S3 buckets.

How:
  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

Why: cdk bootstrap creates CDKToolkit.

What to do: How many primary bootstrap stacks named CDKToolkit does a region usually get?

How:
  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

Why: Modern apps use v2.

What to do: What major version number is AWS CDK v2?

How:
  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

Why: Context caches lookups.

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

How:
  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

Why: Debug failed deploys.

What to do: Describe stack events for amravatiagro-AppStack.

How:
  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

Why: Map constructs to physical ids.

What to do: List stack resources for amravatiagro-AppStack.

How:
  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

Why: Dev then Prod is two.

What to do: If a pipeline deploys Dev then Prod, how many app stages is that?

How:
  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

Why: Expose bucket name.

What to do: JSON Outputs with BucketName Value Ref DataBucket.

How:
  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

Why: Tags flow to resources.

What to do: JSON Tags array one Key Project Value learn.

How:
  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

Why: CDK creates roles too.

What to do: Get IAM role amravatiagro-AppRole.

How:
  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

Why: Function construct maps here.

What to do: Get function configuration for amravatiagro-api.

How:
  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

Why: Deployment role needs rights.

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

How:
  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.