Chapter 1: CDK Overview and Environment Setup

Haiyue
8min

Chapter 1: CDK Overview and Environment Setup

Learning Objectives
  • Understand what AWS CDK is and the problems it solves
  • Learn about the relationship between CDK and CloudFormation
  • Master setting up the CDK development environment
  • Complete the creation of your first CDK application

Knowledge Summary

What is AWS CDK

AWS Cloud Development Kit (CDK) is an open-source software development framework for defining cloud infrastructure resources using familiar programming languages. CDK supports TypeScript, JavaScript, Python, Java, C#/.Net, and Go.

Core Advantages of CDK
  • Type Safety: Compile-time checking reduces runtime errors
  • IDE Support: Code completion, refactoring, debugging, etc.
  • Code Reuse: Reuse infrastructure code through functions, classes, and packages
  • Version Control: Manage infrastructure changes using tools like Git
  • Testing Support: Write unit tests and integration tests

CDK Comparison with Traditional IaC Tools

🔄 正在渲染 Mermaid 图表...

Relationship Between CDK and CloudFormation

🔄 正在渲染 Mermaid 图表...

CDK is actually a high-level abstraction over CloudFormation and ultimately compiles into CloudFormation templates for deployment.

Environment Setup

System Requirements

ToolVersion RequirementDescription
Node.js>= 18.xCDK CLI runtime environment
Python>= 3.8Python CDK application development
AWS CLI>= 2.xAWS access credential configuration
CDK CLILatest versionCDK command-line tool

Installation Steps

# 1. Install Node.js and npm (Node.js must be installed first)

# 2. Install AWS CLI
# pip install awscli

# 3. Configure AWS credentials
# aws configure

# 4. Install CDK CLI
# npm install -g aws-cdk

# 5. Verify installation
# cdk --version

# 6. Install Python CDK library
# pip install aws-cdk-lib constructs
Important Notes
  • CDK CLI requires a Node.js environment, even if you write CDK applications in Python
  • Ensure AWS credentials are properly configured; CDK needs appropriate AWS permissions
  • It’s recommended to use a virtual environment to manage Python dependencies

Your First CDK Application

Creating a New Project

# Create a new CDK application
# cdk init app --language python

# Project structure
# my-cdk-app/
# ├── app.py                 # Application entry file
# ├── cdk.json              # CDK configuration file
# ├── requirements.txt       # Python dependencies
# └── my_cdk_app/
#     ├── __init__.py
#     └── my_cdk_app_stack.py  # Stack definition file

Hello World Example

#!/usr/bin/env python3
# app.py - Application entry file
import aws_cdk as cdk
from my_cdk_app.my_cdk_app_stack import MyCdkAppStack

app = cdk.App()
MyCdkAppStack(app, "MyCdkAppStack")

app.synth()
# my_cdk_app/my_cdk_app_stack.py - Stack definition
from aws_cdk import (
    Duration,
    Stack,
    aws_s3 as s3,
)
from constructs import Construct

class MyCdkAppStack(Stack):
    def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        # Create a simple S3 bucket
        bucket = s3.Bucket(
            self,
            "MyFirstBucket",
            bucket_name="my-first-cdk-bucket-unique-name",
            versioned=True,  # Enable versioning
            removal_policy=cdk.RemovalPolicy.DESTROY  # For development environments
        )

        # Output bucket name
        cdk.CfnOutput(
            self,
            "BucketName",
            value=bucket.bucket_name,
            description="Name of the S3 bucket"
        )

CDK Application Architecture

🔄 正在渲染 Mermaid 图表...

Common CDK Commands

# View available commands
# cdk --help

# List all stacks
# cdk list

# Synthesize CloudFormation template
# cdk synth

# View changes to be deployed
# cdk diff

# Deploy stack
# cdk deploy

# Destroy stack
# cdk destroy

# Initialize Bootstrap
# cdk bootstrap
Bootstrap Explanation

Bootstrap is CDK’s initialization process, which creates necessary infrastructure resources in your AWS account (such as an S3 bucket for storing deployment assets). This only needs to be executed once per AWS account/region combination.

Deployment Process

🔄 正在渲染 Mermaid 图表...

Practical Exercises

  1. Install Environment: Follow the steps above to install the CDK development environment
  2. Create Project: Use cdk init to create your first Python CDK application
  3. Modify Code: Add an S3 bucket to the Stack
  4. Synthesize Template: Use cdk synth to view the generated CloudFormation template
  5. Deploy Application: Use cdk deploy to deploy to AWS
  6. Verify Results: View the created resources in the AWS Console
  7. Clean Up Resources: Use cdk destroy to clean up created resources
Cost Reminder

Even a simple S3 bucket can incur small charges. Remember to clean up resources promptly after completing the exercises.

Troubleshooting

Common Issues

IssueSolution
cdk command not foundEnsure CDK CLI is properly installed
AWS credentials not configuredRun aws configure to configure credentials
Bootstrap requiredRun cdk bootstrap to initialize environment
Insufficient deployment permissionsCheck IAM user permissions

Debugging Tips

# 1. Use synth command to view generated template
# cdk synth --output ./cdk.out

# 2. Use diff command to view changes
# cdk diff

# 3. Enable verbose logging
# cdk deploy --verbose

# 4. Specify a specific stack
# cdk deploy MySpecificStack

This chapter lays the foundation for learning CDK, ensuring you understand the basic concepts of CDK and have successfully set up your development environment.