Section 1: CDK fundamentals
Project setup and the core commands
Let us create a project and run the full cycle.
npm install -g aws-cdk
mkdir orders-service && cd orders-service
cdk init app --language typescript
The generated project contains:
bin/orders-service.ts: creates the App and stacks.lib/orders-service-stack.ts: your first stack.test/: a Jest test file.cdk.json: tells the CLI how to run your app, plus feature flags and context.
Bootstrap once per account and Region
CDK needs a few resources in each target account and Region to deploy assets, such as an S3 bucket for files and an ECR repository for container images, plus roles used during deployment.
cdk bootstrap aws://111122223333/eu-central-1
You run this once per environment, not per project.
The everyday loop
npm run build # compile TypeScript (or rely on ts-node via cdk.json)
cdk synth # print the CloudFormation template
cdk diff # compare with what is deployed
cdk deploy # deploy, asking for approval on security changes
cdk destroy # delete the stack
cdk diff is the most important command for safe work. It shows which resources will be added, modified or replaced. A replacement of a stateful resource such as a database or a bucket should stop you and make you ask why.
cdk deploy also shows a summary of IAM and security group changes and asks for confirmation. Read it. In pipelines, those changes should be reviewed in the pull request instead.
Environments
Stacks can be environment agnostic or bound to an account and Region:
new OrdersStack(app, "OrdersDev", { env: { account: "111122223333", region: "eu-central-1" } });
new OrdersStack(app, "OrdersProd", { env: { account: "444455556666", region: "eu-central-1" } });
Binding environments explicitly lets CDK look up existing resources such as VPCs and availability zones, and makes it impossible to deploy production settings into the wrong account by accident.
Feature flags
cdk.json contains feature flags that change default behaviour for new projects. Leave the generated ones in place; they enable safer modern defaults. When upgrading an old project, read the release notes before turning new flags on.