# CDK

> Source: Courseiva IT Certification Glossary — https://courseiva.com/glossary/cdk

## Quick definition

The AWS CDK lets you write code in languages like Python or TypeScript to create and manage AWS resources. It compiles your code into CloudFormation templates and deploys them automatically. This makes infrastructure setup faster and less error-prone than writing raw templates.

## Simple meaning

Imagine you are building a house. Normally, you would draw a blueprint by hand, making sure every wall, window, and door is perfectly placed. That is like writing a CloudFormation template in YAML or JSON, precise but tedious and easy to mess up. The AWS CDK is like using a smart design app where you describe what you want: “I want a living room here, a kitchen there, and three bedrooms upstairs.” The app then automatically creates the detailed blueprint for you. 

 In technical terms, you write code (like Python or JavaScript) that declares what AWS resources you need, a database, a server, a storage bucket. The CDK takes that code and generates the exact CloudFormation template required to build those resources. This approach is much faster because you can use loops, conditions, and functions that are hard to do in a static template. 

 For example, if you need ten identical servers, instead of copying and pasting the same section ten times in a YAML file, you simply write a loop in your CDK code that says “create ten of these.” This reduces human error and makes your infrastructure easier to maintain and update.

## Technical definition

The AWS Cloud Development Kit (CDK) is an open-source software development framework for defining cloud infrastructure in code and provisioning it through AWS CloudFormation. It was announced at AWS re:Invent 2018 and has matured into a production-grade tool widely used by DevOps teams. 

 CDK works by providing a set of high-level constructs that represent AWS resources. Constructs are the basic building blocks of CDK apps. They can be low-level (representing a single resource like an EC2 instance) or high-level (representing a multi-resource pattern like a load-balanced web application). Developers write code in one of the supported languages: TypeScript, JavaScript, Python, Java, C#, or Go. This code is then synthesized into a CloudFormation template in JSON or YAML format. 

 The CDK uses an engine called the AWS CDK Toolkit (cdk CLI) to interact with the AWS environment. When you run cdk deploy, it first synthesizes your app into a CloudFormation template, then uploads that template to an S3 bucket managed by CloudFormation, and finally triggers a CloudFormation stack creation or update. The CDK also supports features like hotswap deployments for faster iteration, context methods for environment awareness, and the ability to use custom resources via AWS Lambda. 

 Security is built in through AWS Identity and Access Management (IAM) policies. The CDK can automatically generate least-privilege IAM roles for resources based on how they are used in the code. For example, if a Lambda function reads from a DynamoDB table, the CDK can create an IAM role that gives that Lambda read-only access to that specific table. 

 The CDK is not meant to replace CloudFormation but to sit on top of it, making it easier to write and maintain infrastructure as code. It handles complexities like resource dependencies, rollback logic, and change sets transparently.

## Real-life example

Think about planning a large family dinner party. You have a list of guests, a menu, and a seating arrangement. Doing this all manually means writing down each guest's name, what they will eat, and where they sit. If you change the menu, you must update every related note. This is like writing a CloudFormation template by hand. 

 Now imagine using a smart party planner app. You type: “I want 10 guests, a vegetarian option, and tables for groups of four.” The app automatically creates the seating chart, generates shopping lists, and can even adjust everything if someone cancels. This app is like the AWS CDK. You describe the high-level outcome (10 guests, vegetarian) and the app handles the detailed layout. 

 In CDK terms, the guests are like EC2 instances, the menu is like load balancer settings, and the seating chart is like VPC networking. When you code a CDK app, you say “I want an application with two front-end servers and a database,” and CDK writes the full CloudFormation blueprint, including security groups, subnets, and routing rules. If you later decide to add a third server, you just change one number in your code and redeploy.

## Why it matters

For IT professionals, the CDK transforms how you manage cloud infrastructure. Before CDK, writing CloudFormation templates required deep knowledge of YAML or JSON syntax and careful manual tracking of resource dependencies. A small typo could break a deployment, and debugging was painful. CDK lets you use standard programming practices like loops, functions, and version control to manage infrastructure. 

 This matters because modern applications demand speed and reliability. With CDK, you can prototype a new environment in minutes, not hours. It integrates with your existing CI/CD pipeline because the output is just a CloudFormation stack. Teams that adopt CDK report fewer deployment failures and higher developer productivity because they don’t have to switch between a template language and application code. 

 CDK also encourages best practices. For example, the AWS CDK Patterns Library provides tested architectures like “web application with WAF” or “serverless API” that you can reuse. This helps standardize infrastructure across teams and reduces security risk. For a developer associate exam candidate, understanding CDK means you can answer questions about infrastructure automation, IAM roles, and deployment strategies with confidence.

## Why it matters in exams

For the AWS Developer Associate exam, CDK is a relatively new but important topic. While it is not the dominant tool (CloudFormation remains primary), AWS has been increasing CDK’s coverage. The exam objectives under “Development with AWS Services” and “Deployment” include infrastructure as code using CDK. Expect questions that ask you to identify when to use CDK vs. CloudFormation vs. AWS SAM. 

 Questions might present a scenario where a developer needs to quickly create a repeatable infrastructure for a new microservice. The correct answer often involves using CDK because it allows reuse of constructs across services. Another common question type gives you a CDK code snippet and asks what resource it creates or what IAM policy is automatically generated. 

 The AWS Developer Associate exam also tests your understanding of the CDK lifecycle: what does cdk synth do? (It generates the CloudFormation template.) What does cdk diff do? (It shows what changes will be made.) You may be asked to choose the correct command to preview changes before deploying. 

 Since the term is classified as “Small” depth, expect 2-3 questions related to CDK on the exam. You should know the basic CDK workflow, the concept of constructs, and the difference between L1, L2, and L3 constructs. L1 are direct mappings to CloudFormation resources, L2 provide higher-level defaults and helper methods, and L3 are pre-built patterns. This distinction can appear in questions asking which construct level to use for a simple resource vs. a complex architecture.

## How it appears in exam questions

Exam questions about CDK typically fall into three categories: scenario-based, command-based, and code interpretation. Scenario-based questions describe a team that wants to automate infrastructure for multiple environments (dev, test, prod) using code. They need to reuse the same architecture across regions. The correct answer is often CDK because it can accept environment parameters and synthesize different templates. 

 Command-based questions ask about the CDK CLI. For example: “A developer runs cdk synth but wants to see the generated CloudFormation template. Which file should they look for?” Answer: the output is in the cdk.out folder, usually named something like ‘YourStack.template.json’. Another common question: “Which CDK command should be used to show the list of stacks in the app?” Answer: cdk list. 

 Code interpretation questions give a small snippet of TypeScript or Python CDK code. For instance: 

 const bucket = new s3.Bucket(this, ‘MyBucket’, { versioned: true, removalPolicy: cdk.RemovalPolicy.DESTROY }); 

 The question might ask: “What will happen when the stack is deleted?” The removal policy “DESTROY” means the S3 bucket will be deleted along with the stack (only if it is empty). An incorrect option might say the bucket is retained. 

 Troubleshooting questions may involve a deployment failure because of a resource name collision. The solution is to use CDK’s built-in resource naming or to set the “stackName” property to avoid conflicts. Another trap: cdk deploy fails because the user lacks IAM permissions to create resources. The fix is to ensure the IAM user has the appropriate service permissions, not to modify the CDK code.

## Example scenario

You are a developer at a startup building a photo-sharing application. You need to set up an S3 bucket to store user uploads, a DynamoDB table to store image metadata, and a Lambda function to resize images when they are uploaded. 

 Without CDK, you would write three separate CloudFormation resources in YAML, manually set up IAM roles, and hope you didn’t miss a permission. With CDK, you write a single Python file: 

 bucket = s3.Bucket(self, “PhotoBucket”, versioned=False) table = dynamodb.Table(self, “MetadataTable”, partition_key=dynamodb.Attribute(name=“id”, type=dynamodb.AttributeType.STRING)) function = lambda_.Function(self, “ResizerFunction”, runtime=lambda_.Runtime.PYTHON_3_9, handler=“index.handler”, code=lambda_.Code.from_asset(“./lambda”)) bucket.add_event_notification(s3.EventType.OBJECT_CREATED, s3n.LambdaDestination(function)) 

 When you run cdk deploy, CDK automatically creates the IAM role for the Lambda function to read from the S3 bucket. It also creates the DynamoDB table with the correct primary key. If you later need to add a CloudFront distribution, you just add a few more lines. This scenario illustrates how CDK makes infrastructure creation rapid, readable, and maintainable.

## Common mistakes

- **Mistake:** Thinking CDK replaces CloudFormation entirely.
  - Why it is wrong: CDK compiles to CloudFormation templates; it does not bypass CloudFormation. The underlying service used for provisioning is still AWS CloudFormation.
  - Fix: Understand CDK as an abstraction layer over CloudFormation. You still get CloudFormation’s stack management, rollback, and change sets.
- **Mistake:** Not specifying a removal policy when creating a non-production stack.
  - Why it is wrong: By default, CDK sets the retention policy to retain resources when the stack is destroyed. This can lead to orphaned resources costing money.
  - Fix: Use removalPolicy: cdk.RemovalPolicy.DESTROY for development stacks, but be careful with production data. Use cdk.RemovalPolicy.RETAIN for anything you want to keep.
- **Mistake:** Running cdk deploy without first running cdk diff.
  - Why it is wrong: You might accidentally delete or modify important infrastructure. cdk diff shows what changes will be made before deployment.
  - Fix: Always run cdk diff before cdk deploy to review changes. For production environments, consider using a manual approval step in your CI/CD pipeline.
- **Mistake:** Using L1 constructs when L2 constructs would simplify the code.
  - Why it is wrong: L1 constructs map directly to CloudFormation resources and require you to specify every property manually. This defeats the purpose of CDK.
  - Fix: Prefer L2 constructs for common resources like S3 buckets, Lambda functions, and DynamoDB tables. They provide sensible defaults and helper methods.
- **Mistake:** Hardcoding environment-specific values like region or account ID.
  - Why it is wrong: This makes the stack non-portable across accounts and regions. The CDK can use the current environment context automatically.
  - Fix: Use properties from the stack (self.region, self.account) or pass environment parameters via context variables.

## Exam trap

{"trap":"A question states: “A developer wants to deploy infrastructure using AWS CDK. Which service actually provisions the resources?” Options: A) AWS CloudFormation, B) AWS CDK Toolkit, C) AWS CodeDeploy, D) AWS Elastic Beanstalk.","why_learners_choose_it":"Learners sometimes choose B (CDK Toolkit) because they think the CLI directly creates resources. They may not fully understand that CDK is a wrapper around CloudFormation.","how_to_avoid_it":"Remember that the CDK Toolkit (cdk CLI) synthesizes the code into a CloudFormation template and then calls the CloudFormation API to create the stack. CloudFormation is the actual provisioning engine. So the correct answer is A."}

## Commonly confused with

- **CDK vs AWS CloudFormation:** CloudFormation is the underlying service that creates and manages resources from templates. CDK is a tool that writes those templates in a programming language instead of JSON/YAML. (Example: You can think of CloudFormation as the blueprint printer, and CDK as the architect who draws the design in a software tool that outputs the blueprint.)
- **CDK vs AWS SAM (Serverless Application Model):** SAM is a CloudFormation extension focused on serverless applications (Lambda, API Gateway, DynamoDB). CDK is a general-purpose infrastructure tool that can define any AWS resource, including serverless ones. (Example: If you are building a serverless API with Lambda and API Gateway, SAM works well. But if you need an EC2 instance with an auto-scaling group, CDK is better.)
- **CDK vs Terraform (HashiCorp):** Terraform is a cloud-agnostic infrastructure-as-code tool that uses its own HCL language. CDK is AWS-specific and uses general programming languages. Terraform manages resources directly (no CloudFormation), while CDK relies on CloudFormation. (Example: If your company uses multiple cloud providers, you might choose Terraform. If you are all-in on AWS and want to use Python/TypeScript, choose CDK.)

## Step-by-step breakdown

1. **Write CDK App Code** — You create a new CDK project using cdk init app --language=python. This generates a basic directory structure with an entry point file (app.py). You then define your stacks and constructs in separate files.
2. **Synthesize the App** — Run cdk synth. The CDK Toolkit compiles your code into one or more CloudFormation templates. These templates are written in JSON or YAML and stored in the cdk.out directory. This step validates your code against AWS resource schemas.
3. **Bootstrap the Environment (First Time)** — Before first deployment, run cdk bootstrap. This creates an S3 bucket and other resources needed by CDK to store templates and assets. This only needs to be done once per region/account.
4. **Review Changes with Diff** — Run cdk diff to compare the current deployed stack (if any) with the desired state described by your code. It shows additions, modifications, and deletions of resources. This step is critical to avoid unintended changes.
5. **Deploy the Stack** — Run cdk deploy. The CDK Toolkit uploads the synthesized template to the bootstrap S3 bucket and calls the CloudFormation API to create or update the stack. CloudFormation handles dependencies, creates resources, and rolls back if anything fails. You can monitor progress in the AWS Management Console.
6. **Destroy the Stack (When Done)** — Run cdk destroy to delete the stack and its associated resources. Be cautious with production data. The removalPolicy you set in code determines whether resources are kept or deleted. If you used RETAIN, the CloudFormation stack is deleted but the resources remain.

## Practical mini-lesson

When using CDK in a real project, the first decision is which language to choose. Python and TypeScript are most common. TypeScript offers better IDE support for type-checking, while Python is simpler for data scientists and backend developers. 

 The next step is understanding construct levels. L1 constructs (Cfn*) are one-to-one with CloudFormation resources. You must specify every property. Use them only if there is no L2 equivalent. L2 constructs provide a higher-level API with defaults. For example, s3.Bucket automatically adds encryption and versioning defaults. L3 constructs are pre-built patterns like “WebApp with Auto Scaling” or “Serverless API with Auth” from the AWS CDK Patterns library. 

 A key practical concern is managing secrets. Never hardcode passwords or API keys in CDK code. Use AWS Secrets Manager or Systems Manager Parameter Store, and reference them using tokens that CDK resolves at deploy time. For example: ecs.Secret.fromSecretsManager(self, “DbSecret”, “my-db-secret”). 

 Another common task is creating cross-stack references. In CDK, you can pass resources between stacks using stack properties. For example, StackA creates a VPC and exports it as a property. StackB imports that VPC using a CfnOutput and the Fn::ImportValue intrinsic function. CDK handles this transparently by generating the correct CloudFormation references. 

 What can go wrong? The most frequent deployment failure is IAM policy limits. If your code creates too many policies (e.g., for each Lambda version), you might hit AWS service limits. The solution is to use CDK’s iam.PolicyDocument to consolidate permissions. Another issue is stack name collisions when using the same stack name in multiple regions. Use the environment parameter to vary names by region. 

 Professionals also need to configure CI/CD pipelines. The typical pattern is to run cdk synth in the build stage, then run cdk deploy in the deploy stage with proper IAM roles. You can also use CDK Pipelines, a construct that automatically sets up CodePipeline to deploy CDK apps across multiple environments.

## Memory tip

CDK stands for Cloud Development Kit. Remember: You Code, it Deploys the Kit of resources via CloudFormation.

## FAQ

**Do I need to know CloudFormation to use CDK?**

Not necessarily, but it helps. CDK abstracts CloudFormation details, but when things go wrong, you may need to read the generated template to understand errors.

**Can I use CDK with existing CloudFormation templates?**

Yes. You can import existing CloudFormation templates into a CDK app using the CfnInclude construct. This allows you to migrate gradually.

**Is CDK free to use?**

Yes, CDK is open source and free. You only pay for the AWS resources you provision.

**What languages does CDK support?**

TypeScript, JavaScript, Python, Java, C#, and Go (experimental). The most popular are TypeScript and Python.

**How does CDK handle resource dependencies?**

CDK automatically analyzes dependencies between resources and includes the DependsOn attribute in the generated CloudFormation template. You don't need to manage this manually.

**Can I use CDK for non-AWS resources?**

CDK is built for AWS. For multi-cloud infrastructure, consider Terraform. However, AWS CDK has integrations with CloudFormation resource providers that support some third-party resources.

## Summary

The AWS Cloud Development Kit (CDK) is a powerful infrastructure-as-code tool that lets you define AWS resources using general-purpose programming languages. It compiles your code into CloudFormation templates, combining the flexibility of code with the reliability of CloudFormation. 

 For IT certification learners, especially those targeting the AWS Developer Associate exam, CDK represents a modern approach to managing cloud infrastructure. You need to understand the CDK workflow: write code, synthesize, diff, and deploy. Know the difference between construct levels, and be prepared for scenario questions that compare CDK with CloudFormation and SAM. 

 The key exam takeaway is that CDK is not a replacement for CloudFormation, but an abstraction on top. Most exam questions will test your understanding of when to use CDK, the purpose of cdk synth and cdk diff, and the automatic IAM policy generation. With the knowledge of CDK covered in this glossary, you are well-prepared to answer those questions correctly.

---

Practice questions and the full interactive page: https://courseiva.com/glossary/cdk
