hands-on

Learn Python Through AWS CDK: A Hands-On IaC Tutorial

Last updated 2026-11-14

Interactive features. Terminal replays: Play all, Next step, or Replay from start. Diagrams: click or hover over a box for details. "Check yourself" questions give instant feedback. Section ticks in the menu are saved in the browser. Works offline.

Overview

You will learn Python and AWS CDK together: every Python idea is taught with the CDK code where you will actually meet it. No prior Python is assumed. By the end you can write your own stacks, test them, and read other people's CDK code with confidence.

How to practice

  • Type the code yourself instead of copying it. Typing is how the syntax sticks.

  • Run cdk synth after every change and look at what it generated. This is how you connect Python to real AWS resources.

  • Deploy to a personal sandbox AWS account, never production. Run cdk destroy when you finish a session so you are not billed for idle resources.

  • Try each exercise before opening its solution.

Key ideas in plain language

With CDK, you describe the AWS things you want in Python, and AWS builds them for you.

The basics

  • AWS (Amazon Web Services): a company service that rents out computers, file storage, databases and more over the internet. You pay only for what you use.

  • Resource: one single thing you create in AWS. Two you will use here: an S3 bucket (a container for storing files) and a Lambda function (a small piece of your code that AWS runs for you when needed).

  • Infrastructure: all the resources your application needs, taken together.

  • Infrastructure as code (IaC): writing your infrastructure down in a file, instead of creating each resource by hand by clicking through the AWS website. Because it is written down, you can create the same setup again, review changes before they happen, and delete everything cleanly.

What is a stack?

A stack is a group of AWS resources that are created, changed and deleted together, as one unit. This is AWS's own definition (CloudFormation stacks).

Think of a stack as one online shopping order. The order has a name and contains several items. You place the whole order at once, and you can cancel the whole order at once. You never have to remember each item separately.

A small example: a stack named HelloCdkStack contains one bucket and one function.

  • cdk deploy creates the stack, which creates the bucket and the function.

  • If you change your code and deploy again, AWS updates only the resources that changed.

  • cdk destroy deletes the stack, which deletes both resources.

  • If something fails halfway through creating the stack, AWS undoes the whole group for you. This is called a rollback.

Why group things? So nothing gets lost or forgotten. One name covers everything, and one command removes everything.

The word "stack" is used for two things, and both are correct:

"Stack" can meanWhere it livesExample
The Python class where you list your resourcesIn your project filesclass HelloCdkStack(Stack):
The real group of resources AWS created from itIn your AWS account (visible in the CloudFormation page of the AWS website)A stack called HelloCdkStack holding a real bucket

In CDK, a stack is also the smallest thing you can deploy: you deploy whole stacks, never half of one (CDK stacks).

Check yourself You run cdk destroy on a stack that contains one bucket and one function. What is deleted?

The other words you need

WordPlain meaning
CloudFormationThe AWS service that builds stacks. You hand it a list of resources and it creates them in the right order.
TemplateThat list: a text file naming every resource and its settings. CDK writes it for you from your Python.
CDK (Cloud Development Kit)A free toolkit from AWS that turns Python code into templates and sends them to CloudFormation.
CLI (command-line interface)A program you use by typing commands in a terminal. The "CDK CLI" is the cdk command. The "AWS CLI" is the aws command.
ConstructA building block in your code. One Python object that stands for one or more resources, such as s3.Bucket.
AppYour whole CDK project. It holds one or more stacks.
Synth (synthesize)Run your Python and produce the template. Nothing changes in AWS.
DeploySend the template to CloudFormation so it creates or updates the real resources.
DiffShow what a deploy would change, without changing anything.
DestroyDelete a stack and its resources.
cdk synthcdk deploycreateson your computerin your AWS accountYour Python codeapp.py and yourstack classesTemplateA written list ofwhat to buildCloudFormationThe AWS servicethat builds the listA stackYour real resources,managed as one group

Click each box, left to right, to follow your code on its way to AWS.

You write Python, cdk synth turns it into a template, and cdk deploy hands the template to CloudFormation, which creates the stack.

Accounts, Regions and permissions

WordPlain meaning
AWS accountYour private space in AWS, with a 12-digit ID number. Everything you create lives in an account, and the account gets the bill.
Sandbox accountAn account used only for learning and experiments, with nothing important in it. Use one while learning.
RegionA part of the world where AWS has data centers, such as us-west-2 (Oregon). You choose a Region for your resources.
EnvironmentOne account plus one Region. It answers "where does this stack go?"
CredentialsThe keys that prove to AWS who you are, like a username and password for programs.
IAM (Identity and Access Management)The AWS service that controls who is allowed to do what.
PermissionOne allowed action, such as "read files from this bucket".
PolicyA written list of permissions.
RoleA set of permissions that a program or AWS service can use temporarily. A Lambda function gets a role so it can reach other resources.
Least privilegeGiving only the permissions that are truly needed, and no more. This limits the damage if something goes wrong.

1. Setup

You need four tools: Node.js 22 or later, Python 3.10 or later, the AWS CLI, and the CDK CLI. Node.js is required even for Python, because every CDK language runs on the same Node.js backend (prerequisites).

In plain words: a terminal is the window where you type commands. Node.js is a program that runs JavaScript; the cdk command is built with it, but you will never write JavaScript yourself. npm comes with Node.js and installs tools like the CDK CLI. The AWS CLI is Amazon's own command-line tool; here it stores your credentials and lets you check things in your account.

ToolMinimum versionCheck itInstall from
Node.js22.x (an active LTS release)node --versionnodejs.org
Python (with pip and virtualenv)3.10python3 --versionpython.org
AWS CLIv2aws --versionAWS CLI install guide
CDK CLIlatestcdk --versionnpm install -g aws-cdk

What each step changes, before you run anything. Only Step 4 creates anything in AWS. Everything else is local or read-only.

StepCommandChanges your computer?Changes your AWS account?
1aws configure / aws sts get-caller-identityWrites your credentials to ~/.aws/No (read-only check)
2cdk init app --language pythonCreates project files, a git repo and a virtual environmentNo
3source .venv/bin/activate, pip installInstalls packages inside the project folder onlyNo
4cdk bootstrapNoYes: creates a CDKToolkit stack, once per account and Region
5cdk ls, cdk synthWrites templates to cdk.out/No

Step 1: Give the CLI your AWS credentials. Use a sandbox account. If your organization uses IAM Identity Center, run aws configure sso. Otherwise run aws configure. Confirm it works:

aws sts get-caller-identity

What this does: aws configure asks for an access key, secret key, default Region and output format, and saves them in ~/.aws/credentials and ~/.aws/config. (aws configure sso saves a single sign-on profile instead of long-lived keys, which is safer.) The CDK CLI reads these same files later. aws sts get-caller-identity is read-only: it asks AWS "who am I?" and prints your account ID and user or role ARN. If it prints an error, fix your credentials before going further.

Step 2: Create a project. The folder name becomes your project and class names, so use letters, numbers and hyphens only.

mkdir hello-cdk
cd hello-cdk
cdk init app --language python

What cdk init app --language python does. It is a project generator, like a template wizard. It works entirely on your computer: no AWS credentials are used, nothing is created in AWS, and it costs nothing. If you don't like the result, delete the folder and start again.

Reading the command word by word:

PartMeaning
cdkThe CDK CLI you installed with npm
init"Create a new project in the current folder." The folder must be empty.
appWhich template to use. app is an empty, ready-to-fill application. Others: sample-app (an app with example resources) and lib (for publishing a construct library; TypeScript only). Run cdk init --list to see them all.
--language pythonWhich language version of the template to use. Other options include typescript, java, csharp and go.

With CDK CLI 2.1148.1, the command does four things, in this order:

  1. Copied the template files (12 files: app.py, cdk.json, requirements.txt, the hello_cdk/ package and a starter test). It named things after your folder: hello-cdk becomes the Python package hello_cdk and the class HelloCdkStack. Python names can't contain hyphens, so the hyphen becomes an underscore.

  2. Created a git repository and made a first commit called "Initial commit" (only if git is installed). The generated .gitignore keeps .venv/ and cdk.out/ out of git.

  3. Created a Python virtual environment in .venv/: a private copy of Python just for this project.

  4. Installed the dependencies from requirements.txt (aws-cdk-lib and constructs) into that .venv.

It prints a README with next steps and ends with "All done!". Version warnings about pip or the CDK CLI may appear along the way. They are notices only: update with python -m pip install --upgrade pip (inside the virtual environment) and npm install -g aws-cdk (from any shell); you don't need to close the terminal.

The files worth opening now:

  • cdk.json: its "app": "python3 app.py" line tells every later cdk command how to run your code. That is the link between the CLI and your Python. Its context block holds about 90 "feature flags" that switch on the newest recommended CDK behaviors for new projects. Leave them as they are.

  • app.py: creates the App and one HelloCdkStack. It includes two commented-out env= lines that pin the stack to an account and Region (section 8 explains these).

  • hello_cdk/hello_cdk_stack.py: an empty stack with a commented-out SQS queue as an example. This is where your resources will go.

Step 3: Activate the virtual environment and install dependencies. Do the activation every time you open a new terminal for this project.

source .venv/bin/activate        # Windows: .venv\Scripts\activate
python -m pip install -r requirements.txt

What this does: source .venv/bin/activate switches this terminal to the project's private Python. Your prompt gains a (.venv) prefix, and python and pip now point inside .venv/. cdk init created the environment but can't activate it for you, because a program can't change the settings of the shell that started it. That's why you do this step yourself in every new terminal. Run deactivate to switch back.

pip install -r requirements.txt installs every package listed in that file. cdk init already did this, so here it just confirms everything is present and prints "Requirement already satisfied". It is safe to run any time, and you will need it after cloning someone else's project.

If pip reports "No matching distribution found for aws-cdk-lib": the Python in use is too old. Releases of aws-cdk-lib from 2.272.0 onward require Python 3.10 or later (PyPI), and pip hides releases that the running Python cannot use. Check with python --version. If it shows 3.9 or lower, install a newer Python, then rebuild the virtual environment with it:

deactivate
rm -rf .venv
python3.13 -m venv .venv        # use the version you installed
source .venv/bin/activate
python --version                # should now show 3.10 or later
python -m pip install --upgrade pip
python -m pip install -r requirements.txt

Step 4: Bootstrap your account and Region (once per account/Region). This creates the S3 bucket and IAM roles that CDK uses to deploy.

cdk bootstrap aws://123456789012/us-west-2   # your account ID and Region

What this does: this is the only setup step that creates real resources in AWS. CDK deploys through CloudFormation, and it needs somewhere to put your files and permissions to deploy them. cdk bootstrap deploys a CloudFormation stack named CDKToolkit containing (AWS CDK bootstrapping):

ResourceDefault name (in your account and Region)What it's for
S3 bucketcdk-hnb659fds-assets-<account>-<region>Holds the files cdk deploy uploads: zipped Lambda code, other assets, and templates too large to send directly. Versioned; old versions are deleted after 30 days. Kept if you delete the bootstrap stack.
ECR repositorycdk-hnb659fds-container-assets-<account>-<region>Holds Docker images if your app builds any.
Deploy rolecdk-hnb659fds-deploy-role-...The CDK CLI assumes it to start each deployment.
CloudFormation execution rolecdk-hnb659fds-cfn-exec-role-...Handed to CloudFormation, which uses it to create your resources. By default it has the AdministratorAccess policy, so restrict it in shared or production accounts.
File publishing rolecdk-hnb659fds-file-publishing-role-...Used to upload assets to the S3 bucket.
Image publishing rolecdk-hnb659fds-image-publishing-role-...Used to push Docker images to the ECR repository.
Lookup rolecdk-hnb659fds-lookup-role-...Read-only role for lookups such as ec2.Vpc.from_lookup.
SSM parameter/cdk-bootstrap/hnb659fds/versionRecords the bootstrap version, so the CLI knows whether an upgrade is needed.

hnb659fds is CDK's default "qualifier", a fixed ID that lets more than one bootstrap stack exist in the same account if you ever need that. These names and settings come from the bootstrap template itself; you can print it with cdk bootstrap --show-template.

aws://123456789012/us-west-2 names the account and Region to prepare. You need this once per account and Region, not per project: every CDK app in that account and Region shares these resources. You can see the stack in the CloudFormation console afterward.

How they are used in a deploy: your own credentials assume the deploy role. The CLI uploads your assets to the bucket through the publishing roles, then asks CloudFormation to deploy, passing it the execution role (Bootstrap your environment). That is why CloudFormation can create resources even though you never gave it permissions directly.

Cost: the idle roles, repository and parameter cost nothing. The bucket is billed for S3 storage of the assets you deploy, which for small apps is a few small zip files. To remove everything, see "Removing the bootstrap" below.

Step 5: Check that it all works.

cdk ls       # lists your stacks: should print HelloCdkStack
cdk synth    # prints the generated CloudFormation template

What this does: both commands run your Python program using the app line in cdk.json (python3 app.py). Neither deploys anything. cdk ls lists the stacks your code defines. cdk synth (short for synthesize) also writes the generated CloudFormation templates into cdk.out/ and prints them. Since the starter stack is empty, the template contains little more than CDK's own metadata, which is normal. You will add real resources in section 5.

Recommended editor: Visual Studio Code with the Python and Pylance extensions. AWS recommends turning on strict type checking, so mistakes show up as red underlines before you deploy (Working with CDK in Python). Add this to .vscode/settings.json:

{
  "python.languageServer": "Pylance",
  "python.analysis.typeCheckingMode": "strict"
}

Watch it run. Creating the project, one command at a time. Real output from CDK CLI 2.1148.1, shortened. cdk bootstrap is not shown because it needs an AWS account.

Creating the project
$ mkdir hello-cdk
$ cd hello-cdk
$ cdk init app --language python
[... the new project's README is printed here ...]

Initializing a new git repository...
Executing Creating virtualenv...
Executing Installing dependencies...
✅ All done!
$ source .venv/bin/activate
(.venv) $ python -m pip install -r requirements.txt
Requirement already satisfied: aws-cdk-lib<3.0.0,>=2.275.0 in ./.venv/lib/python3.13/site-packages (2.277.0)
Requirement already satisfied: constructs<11.0.0,>=10.5.0 in ./.venv/lib/python3.13/site-packages (10.8.1)
[... more lines like these ...]
(.venv) $ cdk ls
HelloCdkStack

Check yourself Which setup command is the only one that creates something in your AWS account?

Pausing, resuming and undoing each step

Is anything left running when you walk away? On your computer, no. The virtual environment is a folder plus a setting in your terminal, not a running program, and closing the terminal ends it. cdk commands exit when they finish. In AWS, anything you deployed keeps existing until you destroy it. The bootstrap resources sit idle.

Before you stop for the day:

cdk ls                 # the stacks your app defines
cdk destroy --all      # delete every stack this app deployed (asks you to confirm each)
deactivate             # leave the virtual environment (or just close the terminal)

Then confirm nothing is left behind. This lists every active stack in the Region; only CDKToolkit should remain:

aws cloudformation list-stacks \
  --stack-status-filter CREATE_COMPLETE UPDATE_COMPLETE \
  --query "StackSummaries[].StackName"

A resource with RemovalPolicy.RETAIN (the default for S3 buckets and databases) is not deleted by cdk destroy. The sandbox examples use DESTROY to avoid this, but check the S3 console for leftover buckets if you changed that.

When you come back:

cd ~/path/to/hello-cdk          # wherever you created the project
source .venv/bin/activate       # turn the virtual environment back on
aws sts get-caller-identity     # confirm your credentials still work
# If you use IAM Identity Center and this errors with an expired token: aws sso login
cdk ls                          # confirm the app still runs

You don't need to repeat cdk init, pip install or cdk bootstrap. Run cdk deploy again to recreate whatever you destroyed.

Watch it run. Stopping for the day, then coming back. Steps marked "Example output" need an AWS account and show typical output.

Stopping and resuming
(.venv) $ cdk ls
HelloCdkStack
(.venv) $ cdk destroy --all
Are you sure you want to delete: HelloCdkStack (y/n)? y
HelloCdkStack: destroying... [1/1]

 ✅  HelloCdkStack: destroyed
(.venv) $ deactivate
$ # ... later, in a new terminal ...
$ cd ~/hello-cdk
$ source .venv/bin/activate
(.venv) $ aws sts get-caller-identity
{
    "UserId": "AIDAEXAMPLEUSERID",
    "Account": "123456789012",
    "Arn": "arn:aws:iam::123456789012:user/you"
}
(.venv) $ cdk ls
HelloCdkStack

How to undo each step:

StepTo undo itNotes
Install CDK CLInpm uninstall -g aws-cdk
1. CredentialsAccess keys: deactivate or delete the key in the IAM console, then remove its lines from ~/.aws/credentials and ~/.aws/config. SSO: aws sso logout
2. cdk initrm -rf hello-cdkRun cdk destroy --all first. Deleting the folder doesn't delete deployed stacks; you would then have to delete them in the CloudFormation console.
3. Virtual environmentdeactivate. To rebuild it from scratch: rm -rf .venv && python3 -m venv .venv && source .venv/bin/activate && python -m pip install -r requirements.txtSafe: .venv only holds downloaded packages
4. cdk bootstrapSee "Removing the bootstrap" belowOnly once you're completely finished with CDK in that account and Region
5. cdk synthrm -rf cdk.outRecreated on the next synth or deploy
Any deploy (sections 5 to 12)cdk destroy <StackName> or cdk destroy --all

Removing the bootstrap

There is no cdk command to undo bootstrapping. You delete the CDKToolkit stack with CloudFormation, then delete the S3 bucket it leaves behind. Replace us-west-2 with your Region.

  1. Destroy every CDK app stack in that account and Region first. Those stacks use the bootstrap roles for updates and deletion, so they can become hard to delete once the roles are gone.

  2. Note the bucket name (you'll need it in step 4):

    aws cloudformation describe-stacks --stack-name CDKToolkit --region us-west-2 \
      --query "Stacks[0].Outputs[?OutputKey=='BucketName'].OutputValue" --output text
  3. Delete the bootstrap stack and wait for it to finish:

    aws cloudformation delete-stack --stack-name CDKToolkit --region us-west-2
    aws cloudformation wait stack-delete-complete --stack-name CDKToolkit --region us-west-2

    This removes the roles, the ECR repository and the SSM parameter. If it fails because the ECR repository still holds images, delete the repository with aws ecr delete-repository --repository-name cdk-hnb659fds-container-assets-<account>-us-west-2 --force --region us-west-2 and run the delete again.

  4. Delete the retained S3 bucket. In the S3 console, select the bucket, choose Empty (this removes every object and every old version), then Delete. The console is the simplest route because the bucket is versioned, and aws s3 rm doesn't remove old versions.

You can bootstrap again at any time. If you deleted the stack but not the bucket, bootstrapping again fails because the bucket name already exists (Troubleshoot bootstrapping); delete the bucket first.

2. Python basics, part 1: values, collections, logic and functions

This is the Python you will see in almost every CDK file. Try each snippet in the interactive Python shell: run python3, type the code, and type exit() when done.

In plain words: Python is the programming language you will write. A program is a list of instructions the computer follows from top to bottom. You don't need to memorize any of it; read it once, try the snippets, and return when you meet something unfamiliar later.

Watch it run. A short session in the interactive Python shell (start it by typing python3). The >>> prompt means Python is waiting for you to type. Each idea shown here is explained in the sections that follow.

Python shell
>>> env_name = "dev"
>>> f"WebApp-{env_name}"
'WebApp-dev'
>>> type(512)
<class 'int'>
>>> environments = ["dev", "test", "prod"]
>>> environments[0]
'dev'
>>> len(environments)
3
>>> tags = {"Project": "Shop"}
>>> tags["Project"]
'Shop'
>>> tags.get("Missing", "n/a")
'n/a'
>>> [f"queue-{e}" for e in environments]
['queue-dev', 'queue-test', 'queue-prod']

2.1 Comments and indentation

A # starts a comment; Python ignores everything after it on that line. Python uses indentation (4 spaces) instead of braces to group code. A line ending in : starts a block, and every line in that block must be indented the same amount.

# This is a comment
if True:
    print("indented = inside the if block")
print("not indented = outside the block")

Most beginner errors are IndentationError. Let your editor indent for you, and never mix tabs and spaces.

2.2 Variables and basic types

A variable is a name pointing at a value. You do not declare a type; Python works it out.

TypeExampleTypical CDK use
str (text)"prod"construct IDs, tag values, names
int (whole number)30memory size, retention days
float (decimal)0.5thresholds
boolTrue / Falseversioned=True, enforce_ssl=True
NoneNone"no value"; CDK uses it for optional settings
env_name = "dev"
memory_mb = 512
versioned = True
alarm_email = None      # not set yet

print(type(memory_mb))  # <class 'int'>

Naming convention: variables and functions use snake_case (memory_mb), classes use PascalCase (MyS3Stack), and constants use UPPER_CASE (DEFAULT_REGION). CDK's Python API follows the same rules, which is why TypeScript's bucketName becomes bucket_name in Python.

2.3 Strings and f-strings

An f-string puts variables inside text. Put f before the quotes and the variable in {}.

env_name = "dev"
stack_id = f"WebApp-{env_name}"        # "WebApp-dev"
print(stack_id.upper())                 # "WEBAPP-DEV"
print(f"Memory: {512 * 2} MB")          # expressions work too

2.4 Lists: ordered collections

A list holds items in order, inside []. CDK uses lists for things like allowed origins, subnets and IAM actions.

environments = ["dev", "test", "prod"]
print(environments[0])       # "dev"  (counting starts at 0)
print(environments[-1])      # "prod" (negative counts from the end)
print(len(environments))     # 3
environments.append("staging")

actions = ["s3:GetObject", "s3:PutObject"]   # e.g. IAM actions

2.5 Dictionaries: key/value pairs

A dict maps keys to values, inside {}. You will use dicts for configuration and tags.

tags = {"Project": "Shop", "Owner": "platform-team"}
print(tags["Project"])              # "Shop"
tags["CostCenter"] = "1234"         # add or update a key
print(tags.get("Missing", "n/a"))   # .get returns a default instead of crashing

config = {
    "dev":  {"memory": 256,  "retain_data": False},
    "prod": {"memory": 1024, "retain_data": True},
}
print(config["prod"]["memory"])     # 1024 (nested lookup)

AWS's own guide recommends .get() over dict[...] when a key might be missing, because dict[...] raises a KeyError.

2.6 Making decisions: if / elif / else

env_name = "prod"
if env_name == "prod":
    memory = 1024
elif env_name == "test":
    memory = 512
else:
    memory = 256

Comparison operators: == equal, != not equal, <, >, <=, >=. Combine with and, or, not. Check for a missing value with is None:

if alarm_email is not None:
    print(f"Send alarms to {alarm_email}")

AWS recommends making decisions like this in Python at synth time, instead of using CloudFormation Conditions and Parameters.

2.7 Loops: repeating work

A for loop runs once per item. In CDK this is how you create several similar resources without copy-pasting.

for env_name in ["dev", "test", "prod"]:
    print(f"Creating queue for {env_name}")

for key, value in tags.items():       # loop over a dict
    print(key, "=", value)

for i in range(3):                    # 0, 1, 2
    print(i)

A list comprehension builds a new list in one line. You will see these in other people's code:

names = [f"queue-{env}" for env in ["dev", "prod"]]   # ['queue-dev', 'queue-prod']

2.8 Functions: reusable blocks of code

def defines a function. Parameters can have default values, and callers can pass arguments by keyword. Keyword arguments are how every CDK construct is configured, so this is the most important idea here.

def make_name(app: str, env: str = "dev") -> str:
    """Build a consistent name. (This line is a docstring.)"""
    return f"{app}-{env}"

make_name("shop")                 # "shop-dev"  (default used)
make_name("shop", "prod")         # positional arguments
make_name(app="shop", env="prod") # keyword arguments: clearest

Now look at a CDK call. It is just a function call with two positional arguments, then keyword arguments:

s3.Bucket(self, "Uploads",        # positional: scope, id
    versioned=True,               # keyword arguments ("props")
    enforce_ssl=True,
)

The : str and -> str parts are type hints. Python does not enforce them, but your editor uses them to warn you about mistakes. Section 3 covers them.

Try it: write a function bucket_settings(env) that returns a dict with versioned set to True only when env is "prod".

Check yourself In s3.Bucket(self, "Uploads", versioned=True), what is versioned=True?

3. Python basics, part 2: imports, classes and the patterns CDK relies on

Every CDK stack and construct is a Python class. Understanding classes is the key to reading CDK code.

3.1 Modules, packages and imports

A module is a .py file. A package is a folder of modules. import makes code from another module available. These are the import styles AWS recommends for CDK (Working with CDK in Python):

from aws_cdk import App, Stack, Duration     # individual classes from the top level
import aws_cdk as cdk                        # or one alias for many classes (pick one style)
import aws_cdk.aws_s3 as s3                  # service libraries get a short alias
import aws_cdk.aws_lambda as lambda_         # trailing _ because lambda is a Python keyword
from constructs import Construct

The lambda_ name follows the official Python convention: lambda is a reserved word, so a trailing underscore avoids the clash. Your own files import the same way: from hello_cdk.storage import StorageConstruct loads the class StorageConstruct from hello_cdk/storage.py.

3.2 Virtual environments and pip

A virtual environment (.venv) is a private folder of packages for one project, so projects don't conflict. pip installs packages into it. requirements.txt lists what your app needs.

Without a virtual environmentWith a virtual environmentboth install hereOnly one version can be installed at a time,so one of the two projects always breaks.Each project keeps the versions it needs.What activating does in your terminalTo switch back, type deactivate or close the terminal. A virtual environment is only a folder plus aterminal setting. It is not a running program, so nothing is left running when you walk away.Python on your computerOne shared set of packages for everythingProject Aneeds aws-cdk-libversion 2.100Project Bneeds aws-cdk-libversion 2.277Python on your computerLeft alone. Nothing extra is installed here.Project A folder.venvits own Pythonaws-cdk-lib 2.100Project B folder.venvits own Pythonaws-cdk-lib 2.2771. Activatesource .venv/bin/activatePrompt now shows (.venv)2. Type python or pipThe terminal now looks in.venv/bin first3. The private copy runsPackages install into .venv,not the whole computer

Click or hover over a box to read about it.

Why it is needed: a computer can hold only one version of each Python package in its shared location. Two projects that need different versions would break each other. A virtual environment gives each project its own private copy, so projects never interfere, your computer's own Python stays clean, and anyone can rebuild the same setup from requirements.txt.

source .venv/bin/activate              # turn the environment on (every new terminal)
python -m pip install -r requirements.txt
python -m pip install cdk-nag          # add a package...
# ...then add "cdk-nag" to requirements.txt by hand
deactivate                             # turn it off

AWS recommends editing requirements.txt by hand and listing only the packages your app uses directly, instead of using pip freeze. Use ~= (for example aws-cdk-lib~=2.200) to allow compatible upgrades.

Watch it run. See activating change which Python the terminal uses. Folder paths on your computer will differ.

What activate changes
$ which python3
/usr/local/bin/python3
$ source .venv/bin/activate
(.venv) $ which python
/home/you/hello-cdk/.venv/bin/python
(.venv) $ deactivate
$ which python3
/usr/local/bin/python3

Check yourself You close the terminal while a virtual environment is active. What is left running?

3.3 Classes and objects

A class is a blueprint. An object (or instance) is one thing built from it. __init__ is the setup method that runs when you create an object. self means "this particular object".

class Server:
    def __init__(self, name: str, size: str = "small"):
        self.name = name          # attributes: data stored on the object
        self.size = size

    def describe(self) -> str:    # a method: a function that belongs to the class
        return f"{self.name} ({self.size})"

web = Server("web")                       # create an object; __init__ runs
print(web.describe())                     # "web (small)"
db = Server("db", size="large")
print(db.size)                            # "large"

In CDK, s3.Bucket(...) creates a Bucket object, and bucket.bucket_name and bucket.grant_read(...) are an attribute and a method on it.

3.4 Inheritance and super()

A class can inherit from another and gain everything it has. super().__init__(...) runs the parent's setup first. This is exactly what happens in every stack you write:

from aws_cdk import Stack
from constructs import Construct

class MyStack(Stack):                                  # MyStack inherits from Stack
    def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)  # let Stack set itself up
        # ...your resources go here...

Read it in plain English: "MyStack is a kind of Stack. When one is created, first do everything a normal Stack does, then add my resources."

3.5 *args, **kwargs and keyword-only arguments

**kwargs collects any extra keyword arguments into a dict, so you can pass them along without listing each one. A bare * in a parameter list means "everything after this must be passed by keyword".

def show(**kwargs):
    print(kwargs)

show(env="dev", memory=512)       # {'env': 'dev', 'memory': 512}

def create(name: str, *, retain: bool = False):
    ...

create("logs", retain=True)       # OK
# create("logs", True)            # error: retain must be passed by keyword

AWS's guide uses this exact pattern for custom constructs: accept your own options as keyword-only arguments, and pass only **kwargs up to the parent class, because the parent errors on arguments it doesn't know.

class MyConstruct(Construct):
    def __init__(self, scope: Construct, construct_id: str, *, retention_days: int = 30, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)   # don't pass retention_days up

3.6 Type hints

Type hints say what kind of value is expected. They don't change how code runs, but Pylance and mypy use them to catch mistakes. CDK's Python library is fully type-hinted.

from typing import Optional
import aws_cdk.aws_s3 as s3

def add_bucket(self, name: str, versioned: bool = False) -> s3.Bucket: ...
alarm_email: Optional[str] = None      # a str or None (Python 3.10+ also allows: str | None)
subnets: list[str] = []

AWS notes the two most common Python type mistakes in CDK: passing a single value where a list is expected (or the reverse), and mixing low-level CfnXxx types with higher-level constructs. Strict type checking catches both before you deploy.

3.7 Errors and reading a traceback

When something fails, Python prints a traceback. Read it from the bottom up: the last line is the error, and the lines above show which file and line caused it.

Traceback (most recent call last):
  File "app.py", line 8, in <module>
    HelloCdkStack(app, "HelloCdkStack")
  File "hello_cdk/hello_cdk_stack.py", line 12, in __init__
    s3.Bucket(self, "Data", versoned=True)
TypeError: Bucket.__init__() got an unexpected keyword argument 'versoned'

Here the last line says the property name is misspelled (versoned), and the line above it shows exactly where.

Try it: write a class Environment with name and is_prod attributes and a method memory() that returns 1024 for prod and 256 otherwise.

4. Anatomy of a CDK Python project

cdk init app --language python creates the layout below. app.py is the entry point, your stacks live in the package folder, and tests live in tests/.

In plain words: a project is just a folder of files. The entry point is the file that runs first. A dependency is someone else's code that your project needs, such as the CDK library itself.

hello-cdk/
├── app.py                      # entry point: creates the App and your stacks
├── cdk.json                    # tells the CLI how to run your app ("python3 app.py")
├── requirements.txt            # runtime dependencies (aws-cdk-lib, constructs)
├── requirements-dev.txt        # test dependencies (pytest)
├── hello_cdk/                  # your package (folder name, hyphens -> underscores)
│   ├── __init__.py             # marks the folder as a Python package
│   └── hello_cdk_stack.py      # your first stack class
├── tests/unit/
│   └── test_hello_cdk_stack.py # a starter unit test
├── .venv/                      # virtual environment (never commit this)
├── cdk.out/                    # created by synth: templates + assets (never commit)
└── cdk.context.json            # created by lookups: DO commit this
FileWhat it doesDo you edit it?
app.pyCreates the App, creates each stack, calls app.synth()Yes: add stacks and environments here
hello_cdk/*.pyStack and construct classesYes: most of your work
cdk.jsonThe app command plus feature flagsRarely
requirements.txtPackages your app needsYes, when you add a library
tests/pytest tests of the generated templatesYes
cdk.context.jsonCached results of lookups, such as VPC IDsNo, but commit it

AWS recommends committing cdk.context.json so every synth produces the same template, instead of re-querying your account each time.

How the pieces nest: the construct tree

Every CDK app is a tree. The App is the root, stacks sit under it, and constructs sit under stacks. Each object's first argument (scope) says who its parent is. The diagram below shows the tree for a small app.

becomes: AWS::S3::Bucket + BucketPolicybecomes: AWS::Lambda::Function + IAM::RoleApp (root)StorageStack (Stack)scope = appApiStack (Stack)scope = appDataBucket (s3.Bucket)scope = self (the stack)Handler (lambda_.Function)scope = self (the stack)

Click a box to see the line of Python that creates it and its path in the tree.

The construct's path in this tree (for example StorageStack/DataBucket) is what CDK uses to build each resource's CloudFormation logical ID. That is why renaming or moving a construct can replace the resource.

5. Your first stack: a secure S3 bucket

You will create a bucket, look at the CloudFormation it generates, deploy it, and delete it. These four commands are the core CDK loop you will repeat for everything else.

In plain words: you will write one Python class (the stack) that lists one resource (a bucket for storing files). Then you ask CDK to show you the template, send it to AWS so the real bucket exists, and finally delete it again. "Secure" here means four settings: nobody on the public internet can reach the bucket, files are encrypted (scrambled) while stored, connections must use HTTPS, and old versions of files are kept for a while in case of mistakes.

Step 1: Write the stack. Replace the contents of hello_cdk/hello_cdk_stack.py:

from aws_cdk import Stack, RemovalPolicy, CfnOutput, Duration
import aws_cdk.aws_s3 as s3
from constructs import Construct


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

        bucket = s3.Bucket(
            self, "DataBucket",
            block_public_access=s3.BlockPublicAccess.BLOCK_ALL,
            encryption=s3.BucketEncryption.S3_MANAGED,
            enforce_ssl=True,
            versioned=True,
            lifecycle_rules=[
                s3.LifecycleRule(noncurrent_version_expiration=Duration.days(30)),
            ],
            # Learning sandbox only: delete the bucket and its objects on `cdk destroy`.
            # In production, leave the default (RETAIN) so data is never lost by accident.
            removal_policy=RemovalPolicy.DESTROY,
            auto_delete_objects=True,
        )

        CfnOutput(self, "BucketName", value=bucket.bucket_name)

Step 2: Check app.py. It should create your stack. Adding tags here applies them to every resource in the app:

import aws_cdk as cdk
from hello_cdk.hello_cdk_stack import HelloCdkStack

app = cdk.App()
HelloCdkStack(app, "HelloCdkStack")
cdk.Tags.of(app).add("Project", "hello-cdk")
app.synth()

Step 3: Run the CDK loop.

CommandWhat it doesWhen to use it
cdk synthRuns your Python and prints the CloudFormation templateAfter every change, to see what you built
cdk diffCompares your code with what is deployedBefore every deploy; this is your review step
cdk deployUploads assets and deploys through CloudFormationWhen the diff looks right
cdk destroyDeletes the stackWhen you finish practicing

Watch it run. The four commands of the CDK loop, in order. The cdk synth output is real (shortened). The other three need an AWS account, so they show typical example output; your IDs, names and timings will differ.

The CDK loop
(.venv) $ cdk synth
Resources:
  DataBucketE3889A50:
    Type: AWS::S3::Bucket
    Properties:
      BucketEncryption:
        ServerSideEncryptionConfiguration:
          - ServerSideEncryptionByDefault:
              SSEAlgorithm: AES256
      PublicAccessBlockConfiguration:
        BlockPublicAcls: true
        BlockPublicPolicy: true
        IgnorePublicAcls: true
        RestrictPublicBuckets: true
      VersioningConfiguration:
        Status: Enabled
    UpdateReplacePolicy: Delete
    DeletionPolicy: Delete
  DataBucketPolicy3231C704:
    Type: AWS::S3::BucketPolicy
[... about 130 more lines ...]
(.venv) $ cdk diff
Stack HelloCdkStack
Resources
[+] AWS::S3::Bucket DataBucket DataBucketE3889A50
[+] AWS::S3::BucketPolicy DataBucket/Policy DataBucketPolicy3231C704
[+] Custom::S3AutoDeleteObjects DataBucket/AutoDeleteObjectsCustomResource
[+] AWS::IAM::Role Custom::S3AutoDeleteObjectsCustomResourceProvider/Role
[+] AWS::Lambda::Function Custom::S3AutoDeleteObjectsCustomResourceProvider/Handler

Outputs
[+] Output BucketName

✨  Number of stacks with differences: 1
(.venv) $ cdk deploy
✨  Synthesis time: 4.2s

Do you wish to deploy these changes (y/n)? y
HelloCdkStack: deploying... [1/1]
HelloCdkStack: creating CloudFormation changeset...

 ✅  HelloCdkStack

✨  Deployment time: 62.5s

Outputs:
HelloCdkStack.BucketName = hellocdkstack-databuckete3889a50-1a2b3c4d5e6f

✨  Total time: 66.7s
(.venv) $ cdk destroy
Are you sure you want to delete: HelloCdkStack (y/n)? y
HelloCdkStack: destroying... [1/1]

 ✅  HelloCdkStack: destroyed

What to notice in the cdk synth output:

  • One line of Python (enforce_ssl=True) produced a whole AWS::S3::BucketPolicy that denies non-HTTPS requests.

  • auto_delete_objects=True added a custom resource and a small Lambda function that empties the bucket before deletion.

  • The bucket has no fixed name. CDK generates a unique one, which AWS recommends so you can deploy the same stack more than once.

  • The logical ID looks like DataBucketE3889A50: your construct ID plus a hash of its path in the tree.

Step 4: Deploy and clean up.

cdk diff
cdk deploy          # prints Outputs: HelloCdkStack.BucketName = hellocdkstack-databucket...
cdk destroy

Check yourself You want to see what a deploy would change, without changing anything. Which command?

Tokens: values that don't exist yet

bucket.bucket_name is not a real name while your Python runs, because the bucket hasn't been created. It is a token: a placeholder CDK resolves at deploy time. If you print(bucket.bucket_name) you will see something like ${Token[TOKEN.123]}. That is normal. Pass tokens to other constructs, but don't make Python decisions (if, string slicing) on them.

6. Construct levels, props and grants: wiring resources together

Real infrastructure is resources that talk to each other. In CDK you connect them by passing objects around and calling grant methods, which write least-privilege IAM policies for you.

In plain words: in AWS, nothing is allowed to touch anything else until you give permission. A function cannot read a bucket just because both exist. A grant is a one-line way to say "let this function read that bucket", and CDK writes the detailed permission rules (the IAM policy) for you. Props (short for properties) are simply the settings you give a construct.

6.1 The three construct levels

LevelWhat it isHow to spot itUse it when
L1 ("CFN resources")Maps 1:1 to a CloudFormation resource, no defaultsName starts with Cfn, e.g. s3.CfnBucketNo L2 exists yet, or you need a raw CloudFormation property
L2 (curated)One resource with secure defaults and helper methodsPlain name, e.g. s3.Bucket, lambda_.FunctionMost of the time: your default choice
L3 (patterns)Several resources wired together for a common jobUsually in a patterns module, e.g. ecs_patterns.ApplicationLoadBalancedFargateServiceA standard architecture you don't need to customize much

The higher the level, the less you configure and the less expertise you need; the lower the level, the more control you have (AWS CDK Constructs).

Escape hatch: if an L2 lacks a setting, reach its underlying L1 through node.default_child and set the property there:

cfn_bucket = bucket.node.default_child        # the s3.CfnBucket under the L2
cfn_bucket.add_property_override("ObjectLockEnabled", True)

6.2 Props: configuring a construct

Props are the keyword arguments. Nested settings take their own small classes, which you build the same way:

s3.Bucket(self, "Logs",
    lifecycle_rules=[                                   # a list...
        s3.LifecycleRule(                               # ...of LifecycleRule objects
            transitions=[
                s3.Transition(
                    storage_class=s3.StorageClass.GLACIER,   # an enum value
                    transition_after=Duration.days(90),      # a helper for durations
                ),
            ],
        ),
    ],
)

To find every prop, open the construct in the CDK Python API reference or hover over it in VS Code.

6.3 Example: a Lambda function that reads from a bucket

Create the function's code at lambda/list_objects/index.py:

import os
import boto3

s3 = boto3.client("s3")

def handler(event, context):
    bucket = os.environ["BUCKET_NAME"]           # set by CDK below
    response = s3.list_objects_v2(Bucket=bucket, MaxKeys=10)
    keys = [obj["Key"] for obj in response.get("Contents", [])]
    return {"bucket": bucket, "keys": keys}

Then add the function to your stack:

from pathlib import Path
from aws_cdk import Duration
import aws_cdk.aws_lambda as lambda_
import aws_cdk.aws_logs as logs

# inside __init__, after the bucket is created
lister = lambda_.Function(
    self, "ListObjects",
    runtime=lambda_.Runtime.PYTHON_3_14,
    handler="index.handler",                    # file index.py, function handler
    code=lambda_.Code.from_asset(str(Path(__file__).parent.parent / "lambda" / "list_objects")),
    timeout=Duration.seconds(10),
    memory_size=256,
    environment={"BUCKET_NAME": bucket.bucket_name},   # pass the generated name, never hardcode it
    log_group=logs.LogGroup(self, "ListObjectsLogs",
        retention=logs.RetentionDays.ONE_MONTH),        # don't keep logs forever
)

bucket.grant_read(lister)       # one line = a least-privilege IAM policy

What to notice:

  • bucket.grant_read(lister) writes an IAM policy that allows only read actions, on only this bucket, for only this function's role. You never type IAM JSON.

  • environment={"BUCKET_NAME": bucket.bucket_name} passes a token. At deploy time it becomes the real generated name. This is the AWS-recommended way to share names instead of hardcoding them (CDK best practices).

  • Code.from_asset points at a folder. CDK zips it, uploads it during deploy, and wires the function to it. Your runtime code and infrastructure code live in the same project, which AWS recommends.

  • An explicit log group with a retention period stops logs from being kept forever, which is the CDK default.

Which Python runtime? The examples use PYTHON_3_14, the newest generally available Lambda Python runtime. Python 3.15 is in public preview: don't use it for production, because preview runtimes can still change and aren't covered by the Lambda SLA. Lambda's current runtime list is on the Building Lambda functions with Python page.

Run cdk diff. You will see the function, an IAM role, a policy with s3:GetObject*, s3:GetBucket* and s3:List* scoped to your bucket, and a log group. Then test it: aws lambda invoke --function-name <name from the console> out.json.

Common grant methods: bucket.grant_read / grant_write / grant_read_write, table.grant_read_data / grant_read_write_data, queue.grant_send_messages / grant_consume_messages, topic.grant_publish, secret.grant_read.

7. Write your own reusable construct

AWS's top construct guideline is model with constructs, deploy with stacks: group the resources for one feature into a Construct class, then place that construct in whichever stacks need it (CDK best practices). Here you build an UploadProcessor: a bucket that triggers a Lambda function for every new file.

In plain words: so far you have used building blocks that AWS wrote. Now you make your own. A custom construct bundles several resources that belong together into one reusable piece, so you can create the whole bundle with a single line, as many times as you like. "Model with constructs, deploy with stacks" means: describe each feature as a construct, and use stacks only to decide what gets deployed together.

Step 1: The construct. Create hello_cdk/upload_processor.py:

from aws_cdk import Duration, RemovalPolicy
import aws_cdk.aws_s3 as s3
import aws_cdk.aws_s3_notifications as s3n
import aws_cdk.aws_lambda as lambda_
import aws_cdk.aws_logs as logs
from constructs import Construct


class UploadProcessor(Construct):
    """An S3 bucket that runs a Lambda function for every new object."""

    def __init__(
        self,
        scope: Construct,
        construct_id: str,
        *,                                    # everything below must be passed by keyword
        handler_path: str,                    # required: folder holding index.py
        memory_size: int = 256,               # optional, with sensible defaults
        removal_policy: RemovalPolicy = RemovalPolicy.RETAIN,
        **kwargs,
    ) -> None:
        super().__init__(scope, construct_id, **kwargs)   # only kwargs go to the parent

        # Public attributes (self.xxx) let other code use what this construct creates.
        self.bucket = s3.Bucket(
            self, "Bucket",
            block_public_access=s3.BlockPublicAccess.BLOCK_ALL,
            encryption=s3.BucketEncryption.S3_MANAGED,
            enforce_ssl=True,
            removal_policy=removal_policy,
            auto_delete_objects=(removal_policy == RemovalPolicy.DESTROY),
        )

        self.function = lambda_.Function(
            self, "Handler",
            runtime=lambda_.Runtime.PYTHON_3_14,
            handler="index.handler",
            code=lambda_.Code.from_asset(handler_path),
            memory_size=memory_size,
            timeout=Duration.seconds(30),
            log_group=logs.LogGroup(self, "HandlerLogs", retention=logs.RetentionDays.ONE_MONTH),
        )

        self.bucket.grant_read(self.function)
        self.bucket.add_event_notification(
            s3.EventType.OBJECT_CREATED,
            s3n.LambdaDestination(self.function),
        )

Step 2: The handler. Create lambda/process_upload/index.py:

def handler(event, context):
    for record in event["Records"]:
        key = record["s3"]["object"]["key"]
        print(f"New upload: {key}")      # appears in CloudWatch Logs

Step 3: Use it, twice, in a stack.

from pathlib import Path
from aws_cdk import Stack, RemovalPolicy, CfnOutput
from constructs import Construct
from hello_cdk.upload_processor import UploadProcessor

HANDLER = str(Path(__file__).parent.parent / "lambda" / "process_upload")


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

        images = UploadProcessor(self, "Images", handler_path=HANDLER, memory_size=512,
                                 removal_policy=RemovalPolicy.DESTROY)
        documents = UploadProcessor(self, "Documents", handler_path=HANDLER,
                                    removal_policy=RemovalPolicy.DESTROY)

        CfnOutput(self, "ImagesBucket", value=images.bucket.bucket_name)
        CfnOutput(self, "DocumentsBucket", value=documents.bucket.bucket_name)

Register it in app.py with ProcessingStack(app, "ProcessingStack"), then run cdk synth. Two calls produced two complete, independent sets of resources. Their paths in the tree are ProcessingStack/Images/Bucket and ProcessingStack/Documents/Bucket, so their IDs never collide.

Design rules for your own constructs

  • Take settings as keyword-only props with safe defaults; never read environment variables inside a construct.

  • Expose what callers need (self.bucket, self.function) as attributes.

  • Default to safe choices (RETAIN, encryption, no public access) and make callers opt out explicitly.

  • Keep construct IDs stable once deployed. Renaming "Bucket" later changes the logical ID and replaces the bucket.

  • Wrappers like this are useful, but AWS warns they are not enough for compliance on their own. Back them with organization-level controls and checks such as cdk-nag (section 10).

8. Multiple stacks, environments and configuration

A real app splits into stacks by how they are deployed, runs in several environments (dev, prod), and keeps per-environment settings in one place. AWS suggests keeping stateful resources (databases, buckets) in their own stack with termination protection, so you can freely destroy and recreate the stateless parts (CDK best practices).

In plain words: a stateful resource stores data you would be upset to lose, such as a bucket of files or a database. A stateless resource stores nothing important and can be deleted and rebuilt at any time, such as a Lambda function. Keeping them in separate stacks means you can rebuild the replaceable parts without ever touching your data. Termination protection is a safety switch that makes AWS refuse to delete a stack until you turn the switch off. "Dev" and "prod" are short for development (where you experiment) and production (the real thing your users rely on).

8.1 Configuration in one typed place

A dataclass is a short way to write a class that just holds data. frozen=True makes it read-only. Create hello_cdk/config.py:

from dataclasses import dataclass


@dataclass(frozen=True)
class StageConfig:
    name: str
    account: str
    region: str
    lambda_memory: int
    is_prod: bool


STAGES = {
    "dev":  StageConfig("dev",  "111111111111", "us-west-2", lambda_memory=256,  is_prod=False),
    "prod": StageConfig("prod", "222222222222", "us-west-2", lambda_memory=1024, is_prod=True),
}

The @dataclass line is a decorator: it adds behavior to the class below it (here, an automatic __init__). Values are committed to source control, so every deploy is reproducible and reviewable.

8.2 A stateful stack and a stateless stack

# hello_cdk/storage_stack.py
from aws_cdk import Stack, RemovalPolicy
import aws_cdk.aws_s3 as s3
from constructs import Construct
from hello_cdk.config import StageConfig


class StorageStack(Stack):
    def __init__(self, scope: Construct, construct_id: str, *, config: StageConfig, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)
        self.bucket = s3.Bucket(
            self, "DataBucket",
            enforce_ssl=True,
            versioned=config.is_prod,
            removal_policy=RemovalPolicy.RETAIN if config.is_prod else RemovalPolicy.DESTROY,
            auto_delete_objects=not config.is_prod,
        )
# hello_cdk/api_stack.py
import aws_cdk.aws_s3 as s3
# ...same imports as section 6...

class ApiStack(Stack):
    def __init__(self, scope: Construct, construct_id: str, *,
                 config: StageConfig, bucket: s3.IBucket, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)
        fn = lambda_.Function(self, "Handler",
            runtime=lambda_.Runtime.PYTHON_3_14,
            handler="index.handler",
            code=lambda_.Code.from_asset("lambda/list_objects"),
            memory_size=config.lambda_memory,
            environment={"BUCKET_NAME": bucket.bucket_name},
        )
        bucket.grant_read(fn)

The type s3.IBucket is an interface: "anything that behaves like a bucket". Using it means the stack also accepts an existing bucket imported with s3.Bucket.from_bucket_name(...).

8.3 Wiring it together in app.py

import aws_cdk as cdk
from hello_cdk.config import STAGES
from hello_cdk.storage_stack import StorageStack
from hello_cdk.api_stack import ApiStack

app = cdk.App()
stage_name = app.node.try_get_context("stage") or "dev"   # cdk deploy -c stage=prod
config = STAGES[stage_name]
env = cdk.Environment(account=config.account, region=config.region)

storage = StorageStack(app, f"Storage-{config.name}", config=config, env=env,
                       termination_protection=config.is_prod)
ApiStack(app, f"Api-{config.name}", config=config, bucket=storage.bucket, env=env)

cdk.Tags.of(app).add("Stage", config.name)
app.synth()

How the cross-stack reference works: passing storage.bucket into ApiStack makes CDK create a CloudFormation export in the storage stack and an import in the API stack, and it deploys them in the right order automatically. This is the AWS-recommended pattern when both stacks are in the same app. For a stack in a different CDK app, use a from_... method such as s3.Bucket.from_bucket_arn(...) instead.

Deploy commands:

cdk deploy --all                     # dev (the default)
cdk deploy --all -c stage=prod       # prod
cdk deploy Api-dev                   # just one stack

About env: set account and Region explicitly for production stacks. For personal dev stacks you can use cdk.Environment(account=os.getenv("CDK_DEFAULT_ACCOUNT"), region=os.getenv("CDK_DEFAULT_REGION")), which picks up whatever credentials the CLI is using. A stack with no env is "environment-agnostic" and can't use lookups such as ec2.Vpc.from_lookup (Stack API reference).

Check yourself Which of these is a stateful resource that deserves extra protection?

9. Testing your infrastructure with pytest

CDK tests synthesize a stack in memory and check the generated template. They need no AWS account and run in seconds, so run them on every change. AWS lists unit-testing infrastructure as a core best practice, and recommends asserting that stateful resources keep their logical IDs.

In plain words: a test is a small piece of code that checks your other code does what you expect. Each test makes a claim, such as "the bucket is encrypted". If the claim is true the test passes; if not, it fails and tells you why. pytest is the tool that finds and runs your tests. A unit test checks one small piece on its own.

Setup: install the test tools and run the starter test.

python -m pip install -r requirements-dev.txt     # installs pytest
python -m pytest                                   # runs everything in tests/

A test file, tests/unit/test_hello_cdk_stack.py:

import aws_cdk as cdk
from aws_cdk.assertions import Template, Match
from hello_cdk.hello_cdk_stack import HelloCdkStack


def make_template() -> Template:
    app = cdk.App()
    stack = HelloCdkStack(app, "TestStack")
    return Template.from_stack(stack)           # synthesize in memory


def test_bucket_is_versioned_and_encrypted():
    template = make_template()
    template.has_resource_properties("AWS::S3::Bucket", {
        "VersioningConfiguration": {"Status": "Enabled"},
        "BucketEncryption": Match.object_like({          # only check the keys we list
            "ServerSideEncryptionConfiguration": Match.any_value(),
        }),
    })


def test_public_access_is_blocked():
    template = make_template()
    template.has_resource_properties("AWS::S3::Bucket", {
        "PublicAccessBlockConfiguration": {
            "BlockPublicAcls": True,
            "BlockPublicPolicy": True,
            "IgnorePublicAcls": True,
            "RestrictPublicBuckets": True,
        },
    })


def test_exactly_one_bucket():
    make_template().resource_count_is("AWS::S3::Bucket", 1)


def test_bucket_logical_id_never_changes():
    # Copy the real ID from `cdk synth` once; if a refactor changes it, this test fails
    # before a deploy could replace (and empty) your bucket.
    buckets = make_template().find_resources("AWS::S3::Bucket")
    assert "DataBucketE3889A50" in buckets          # replace with your actual ID
AssertionWhat it checks
has_resource_properties(type, props)At least one resource of that type has these properties
resource_count_is(type, n)Exactly n resources of that type
find_resources(type)Returns matching resources as a dict keyed by logical ID, for your own asserts
Match.object_like({...})Only the listed keys must match; others are ignored
Match.any_value()The key must exist, with any value
Match.array_with([...])The list contains these items, among others

Full reference: aws_cdk.assertions.

Watch it run. Tests passing, then catching a mistake, then passing again. Real output, shortened.

Running the tests
(.venv) $ python -m pytest
============================= test session starts ==============================
platform linux -- Python 3.13.18, pytest-8.4.2, pluggy-1.7.0
collected 3 items

tests/unit/test_hello_cdk_stack.py ...                                   [100%]

============================== 3 passed in 2.14s ===============================
(.venv) $ # now break the code on purpose: change versioned=True to versioned=False
(.venv) $ python -m pytest
[... long error details ...]
E   RuntimeError: AssertionError: Template has 1 resources with type AWS::S3::Bucket, but none match as expected.
E   !!   Missing key 'VersioningConfiguration'
=========================== short test summary info ============================
FAILED tests/unit/test_hello_cdk_stack.py::test_bucket_is_versioned_and_encrypted
========================= 1 failed, 2 passed in 2.39s ==========================
(.venv) $ # change it back to versioned=True
(.venv) $ python -m pytest
tests/unit/test_hello_cdk_stack.py ...                                   [100%]

============================== 3 passed in 2.14s ===============================

What to test: security settings (encryption, public access, SSL), the IAM permissions a grant produced, resource counts, and the logical IDs of stateful resources. Don't test things the CDK library already guarantees. Write a test, break the code on purpose (set versioned=False), and watch the test fail. That is how you know the test works.

Also run in CI: pyright or mypy app.py for type errors, and cdk synth so cdk-nag findings fail the build (section 10).

10. Best practices checklist

These practices come from AWS's official Best practices for developing and deploying cloud infrastructure with the AWS CDK, with the Python way to apply each one. Use the table as a review checklist for your own code and for AI-generated code.

In plain words: a best practice is a habit that experienced people follow because it prevents common problems. A few terms in the table: CI/CD is an automated system that tests and deploys your code for you whenever you save changes to the shared copy. Service control policies (SCPs) and permission boundaries are account-wide safety limits set by an administrator that no project can exceed. A logical ID is the name CloudFormation uses to track each resource inside a stack.

PracticeWhy it mattersHow, in Python
Start simple; add complexity only when neededYou can refactor later; don't design for every scenario up frontOne stack, L2 constructs, add more when a real need appears
Model with constructs, deploy with stacksConstructs are reusable; stacks are just units of deploymentFeature = a Construct class (section 7); stacks only compose them
Configure with props, not environment variablesEnv-var lookups tie the code to one machineKeyword-only props; read os.getenv only at the top of app.py
Make decisions at synth timePython if/for are far more capable than CloudFormation Conditions/Parametersif config.is_prod: instead of CfnParameter and CfnCondition
Use generated names, not physical namesHardcoded names block a second deployment and break replacementsOmit bucket_name, function_name, table_name; pass bucket.bucket_name
Don't change logical IDs of stateful resourcesA new logical ID replaces the resource: an empty new bucket or databaseKeep construct IDs and nesting stable; test the IDs (section 9)
Define removal policies and log retentionDefaults retain data and keep logs forever, which costs moneySet removal_policy on each stateful resource; set log retention
Separate stateful from stateless stacksDestroy and recreate stateless parts without risking dataA storage stack with termination_protection=True (section 8)
Commit cdk.context.jsonLookups are cached, so every synth gives the same templategit add cdk.context.json
Never change AWS during synthSynth must be side-effect free so CloudFormation can roll backNo boto3 write calls in stack code; use custom resources if needed
Let CDK manage roles and security groupsGrants produce minimal, correct permissionsbucket.grant_read(fn); newer releases also offer bucket.grants.read(fn)
Model all production stages in codeEvery commit yields the same templates for every environmentA config per stage in code (section 8); secrets in Secrets Manager or Parameter Store
Unit test your infrastructureCatches regressions before deploypytest + aws_cdk.assertions (section 9)
Don't rely on wrapper constructs for complianceWrappers can be bypassedcdk-nag or CloudFormation Guard, plus SCPs and permission boundaries
Measure everythingYou can't automate deployments you can't observeL2 metric_* methods, CloudWatch alarms and dashboards

Add automated security checks with cdk-nag

cdk-nag is an open-source rule pack from AWS Labs. It checks every resource during synth and fails the build when a resource breaks a rule (for example, a bucket with no server access logging). cdk-nag v3 (released June 2026) changed its API. It now plugs into CDK's built-in Validations framework, and the old Aspects and NagSuppressions code you will see in older examples no longer works. Install it with python -m pip install cdk-nag and add cdk-nag to requirements.txt. Then, in app.py:

import aws_cdk as cdk
from cdk_nag import AwsSolutionsChecks
from hello_cdk.hello_cdk_stack import HelloCdkStack

app = cdk.App()
stack = HelloCdkStack(app, "HelloCdkStack")

# Check everything in the app against the AWS Solutions rule pack
cdk.Validations.of(app).add_plugins(AwsSolutionsChecks(app, verbose=True))

# Accept a rule deliberately, one rule per call, with a reason a reviewer can read.
# The ID is the one cdk-nag prints after "Acknowledge with".
cdk.Validations.of(stack).acknowledge(
    cdk.Acknowledgment(id="AwsSolutions::AwsSolutions-S1",
                       reason="Sandbox bucket; access logs not required"),
)
app.synth()

Now cdk synth fails with a report listing each finding, its construct path, and the exact ID to acknowledge. Fix the finding, or acknowledge it with a real reason; acknowledgments are easy for reviewers to scan. Expect findings even on small, well-built examples. For example, AwsSolutions-L1 flags Python 3.14 functions because cdk-nag treats the 3.15 preview as the latest runtime, and AwsSolutions-IAM5 flags the /* object wildcard that grant_read correctly creates.

Habits that prevent most incidents

  • Run cdk diff before every deploy, and read every line that says replace or destroy.

  • Deploy production only from a CI/CD pipeline (CDK Pipelines or similar), never from a laptop.

  • Pin aws-cdk-lib with ~= in requirements.txt and upgrade on purpose.

  • Keep secrets out of code: store them in Secrets Manager and reference them by name or ARN.

11. How to read other people's CDK code

Start from app.py and work down the tree, then confirm what you think the code does against cdk synth. The generated template is the ground truth.

  1. Read cdk.json. The app line tells you the entry file (usually python3 app.py). The context block holds feature flags and settings the code may read.

  2. Read app.py top to bottom. List every stack it creates, the env (account and Region) each gets, and what is passed between stacks. This is the app's map.

  3. Run cdk ls to confirm the stack names, then cdk synth <StackName> for the one you care about.

  4. Open one stack class. Skip the imports and super().__init__ line; read the body. For each construct, note three things: its class (what kind of resource), its ID (second argument), and its props (keyword arguments).

  5. Follow custom constructs. When you see an unfamiliar class like UploadProcessor(...), find where it's imported and read its __init__. Look for self.xxx = lines to see what it exposes.

  6. Trace the connections. Search for grant_, add_event_, environment=, and constructor arguments that receive another construct. These are the data flows and permissions.

  7. Look up anything unfamiliar in the CDK Python API reference. Every prop and method is documented there.

  8. Check the safety settings: removal_policy, hardcoded names, Cfn (L1) constructs or add_property_override (escape hatches), NagSuppressions and their reasons.

  9. Read the tests. tests/ shows what the author thought was important to guarantee.

Walk through it. The nine steps applied to the S3 bucket project from section 5. The highlighted lines are the ones to look at.

Python you'll meet in other people's code

You seeIt means
@dataclass, @jsii.implements(IAspect)A decorator: adds behavior to the function or class below it
[x.name for x in items if x.enabled]List comprehension: build a list in one line
key=lambda r: r["date"]A small anonymous function (this lambda is Python's keyword, unrelated to AWS Lambda)
value = a if condition else bOne-line if/else
Optional[str], str | NoneType hint: a string or nothing
def __init__(self, scope, id, *, props: MyProps, **kwargs)Keyword-only props bundled in a props class
Stack.of(self)The stack this construct sits in, often used for .region or .account
self.node.try_get_context("key")Reads a value from cdk.json or -c key=value; returns None if missing
Fn.import_value(...), CfnOutput(..., export_name=...)Manual cross-stack exports and imports
ec2.Vpc.from_lookup(...), s3.Bucket.from_bucket_arn(...)References an existing resource instead of creating one
if __name__ == "__main__":Code that runs only when the file is executed directly
_lambda instead of lambda_Another naming style for the Lambda module: same thing

Ask these questions of any CDK code

  • What will this create, change or delete? (Run cdk diff.)

  • Which resources hold data, and what happens to them if the stack is deleted?

  • Who can access what? (Follow every grant and policy.)

  • Is anything hardcoded that should be generated or configured: names, account IDs, ARNs, secrets?

  • Would a refactor change a stateful resource's ID?

12. Practice exercises with solutions

Try each exercise in your own project before reading the solution. Run cdk synth and your tests after every change.

Exercise 1 (Python): settings function

Write bucket_settings(env) that returns a dict with versioned set to True only for "prod", and retain set the same way.

Show solution
def bucket_settings(env: str) -> dict:
    is_prod = env == "prod"
    return {"versioned": is_prod, "retain": is_prod}

print(bucket_settings("dev"))    # {'versioned': False, 'retain': False}

Exercise 2 (Python): a class

Write a class Environment with name and is_prod attributes and a memory() method returning 1024 for prod, otherwise 256.

Show solution
class Environment:
    def __init__(self, name: str, is_prod: bool = False):
        self.name = name
        self.is_prod = is_prod

    def memory(self) -> int:
        return 1024 if self.is_prod else 256

print(Environment("prod", is_prod=True).memory())   # 1024

Exercise 3 (CDK): a queue with a dead-letter queue and a consumer

In a new stack, create an SQS queue whose failed messages go to a dead-letter queue after 3 attempts, and a Lambda function that processes the main queue.

Show solution
from aws_cdk import Stack, Duration
import aws_cdk.aws_sqs as sqs
import aws_cdk.aws_lambda as lambda_
from aws_cdk.aws_lambda_event_sources import SqsEventSource
from constructs import Construct


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

        dlq = sqs.Queue(self, "JobsDlq",
            retention_period=Duration.days(14),
            enforce_ssl=True,
        )
        jobs = sqs.Queue(self, "Jobs",
            visibility_timeout=Duration.seconds(180),   # comfortably longer than the function timeout
            dead_letter_queue=sqs.DeadLetterQueue(max_receive_count=3, queue=dlq),
            enforce_ssl=True,
        )

        worker = lambda_.Function(self, "Worker",
            runtime=lambda_.Runtime.PYTHON_3_14,
            handler="index.handler",
            code=lambda_.Code.from_inline(
                "def handler(event, context):\n    print(len(event['Records']), 'messages')"),
            timeout=Duration.seconds(30),
        )
        worker.add_event_source(SqsEventSource(jobs, batch_size=10))  # also grants consume permissions

Exercise 4 (CDK + Python): one queue per team with a loop

Given TEAMS = ["billing", "search", "orders"], create one queue per team and keep them in a dict keyed by team name.

Show solution
TEAMS = ["billing", "search", "orders"]

self.queues: dict[str, sqs.Queue] = {}
for team in TEAMS:
    self.queues[team] = sqs.Queue(self, f"{team.capitalize()}Queue", enforce_ssl=True)

# Later: self.queues["billing"].grant_send_messages(some_function)

Note that each construct ID (BillingQueue, SearchQueue) comes from the team name. Renaming a team later would replace its queue.

Exercise 5 (testing): prove the dead-letter queue works

Write tests for Exercise 3: the main queue has a redrive policy with 3 receives, and there are exactly 2 queues.

Show solution
import aws_cdk as cdk
from aws_cdk.assertions import Template, Match
from hello_cdk.queue_stack import QueueStack


def test_queue_has_dlq():
    template = Template.from_stack(QueueStack(cdk.App(), "Test"))
    template.resource_count_is("AWS::SQS::Queue", 2)
    template.has_resource_properties("AWS::SQS::Queue", {
        "RedrivePolicy": Match.object_like({"maxReceiveCount": 3}),
    })

Exercise 6 (code review): find the problems

This construct works, but it breaks several best practices. List as many problems as you can.

import os

class ReportsConstruct(Construct):
    def __init__(self, scope, id):
        super().__init__(scope, id)
        stage = os.environ["STAGE"]
        bucket = s3.Bucket(self, "Reports", bucket_name="acme-reports")
        role = iam.Role(self, "Role", assumed_by=iam.ServicePrincipal("lambda.amazonaws.com"))
        role.add_to_policy(iam.PolicyStatement(actions=["s3:*"], resources=["*"]))
Show solution
  1. Reads an environment variable inside a construct; take stage as a prop instead.

  2. os.environ["STAGE"] crashes with KeyError if the variable isn't set.

  3. Hardcoded bucket_name means the stack can't be deployed twice and the bucket can't be replaced.

  4. s3:* on * grants every S3 action on every bucket in the account. Use bucket.grant_read(...) instead.

  5. A hand-built role where a grant on the function's own role would do.

  6. Missing enforce_ssl=True and an explicit removal policy.

  7. bucket is a local variable, so callers can't use it; store it as self.bucket.

  8. The parameter named id shadows Python's built-in id(); use construct_id. No type hints, so the editor can't help.

Run cdk-nag on it to see how many of these it flags automatically.

13. Cheat sheet

CLI commands

CommandPurpose
cdk init app --language pythonNew project
source .venv/bin/activateTurn on the virtual environment
cdk bootstrap aws://ACCOUNT/REGIONOne-time setup per account and Region
cdk lsList stacks
cdk synth [Stack]Generate and show the CloudFormation template
cdk diff [Stack]Show what a deploy would change
cdk deploy [Stack | --all] [-c key=value]Deploy
cdk destroy [Stack]Delete a stack
cdk migrate --from-scan --stack-name X --language pythonGenerate CDK from existing resources
python -m pytestRun infrastructure tests

Code patterns

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

# Construct skeleton with props
class MyThing(Construct):
    def __init__(self, scope: Construct, construct_id: str, *, size: int = 1, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

# Every construct: scope, id, then props
bucket = s3.Bucket(self, "Data", enforce_ssl=True)

# Permissions
bucket.grant_read(fn)

# Pass generated names, never hardcode
environment={"BUCKET_NAME": bucket.bucket_name}

# Durations, removal and tags
Duration.seconds(30); Duration.days(7)
RemovalPolicy.RETAIN   # or DESTROY for sandboxes
cdk.Tags.of(app).add("Project", "shop")

# Outputs, context, existing resources
CfnOutput(self, "Name", value=bucket.bucket_name)
self.node.try_get_context("stage")
s3.Bucket.from_bucket_name(self, "Existing", "my-existing-bucket")

Where to look things up

Glossary

Short, plain definitions in alphabetical order. The core ideas (stack, template, construct, app, Region, IAM) are explained under "Key ideas in plain language".

TermPlain meaning
API referenceThe official list of every construct and setting, where you look things up
ARNAmazon Resource Name: the full, unique address of one resource in AWS
AssetA file from your computer that CDK uploads during a deploy, such as zipped Lambda code
AttributeA piece of data stored on an object, such as bucket.bucket_name
BootstrapThe one-time setup that gives CDK a storage bucket and permissions in your account
Bucket (S3)A container in AWS for storing files
ClassA blueprint in Python for making objects
CloudWatch LogsThe AWS service where programs such as Lambda functions write their log messages
Construct IDThe name you give a construct (its second argument), unique within its parent
ContextSmall settings passed to your app, from cdk.json or with -c key=value
Cross-stack referenceOne stack using a resource that another stack created
Custom resourceA helper CDK adds to do a job CloudFormation can't do alone, such as emptying a bucket
Dead-letter queueA second queue that collects messages that kept failing, so they aren't lost
EncryptionScrambling data so only authorized parties can read it
EnumA fixed list of allowed choices, such as s3.BucketEncryption.S3_MANAGED
Escape hatchA way to set a low-level option that the high-level construct doesn't offer
GrantA one-line way to give one resource permission to use another
HandlerThe function inside your Lambda code that AWS calls
L1, L2, L3Three levels of construct, from raw and detailed (L1) to ready-made patterns (L3)
Lambda functionA small piece of your code that AWS runs on demand, with no server for you to manage
Log groupA named place in CloudWatch Logs holding one program's log messages
Logical IDThe name CloudFormation uses for a resource inside a stack
MethodA function that belongs to an object, such as bucket.grant_read()
ObjectOne thing made from a class
OutputA value a stack prints after deploying, such as a generated bucket name
PackageA folder of Python code that can be installed or imported
PropsThe settings you pass to a construct as keyword arguments
Queue (SQS)A waiting line of messages that one program writes and another reads
Removal policyWhat happens to a resource when it leaves the stack: keep it (RETAIN) or delete it (DESTROY)
RollbackAWS undoing a failed deploy so the stack returns to its last working state
RuntimeThe language and version a Lambda function runs on, such as Python 3.14
ScopeA construct's parent (its first argument), usually self
Stateful / statelessHolding data you must not lose / holding nothing that can't be rebuilt
TokenA placeholder for a value that isn't known until deploy time
TracebackPython's error report, read from the bottom up
Virtual environmentA private folder of Python packages for one project

Sources

Code in sections 5 through 12 verified with aws-cdk-lib 2.277.0 and cdk-nag 3.0.2 on November 14, 2026.