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 synthafter 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 destroywhen 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 deploycreates 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 destroydeletes 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 mean | Where it lives | Example |
|---|---|---|
| The Python class where you list your resources | In your project files | class HelloCdkStack(Stack): |
| The real group of resources AWS created from it | In 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
| Word | Plain meaning |
|---|---|
| CloudFormation | The AWS service that builds stacks. You hand it a list of resources and it creates them in the right order. |
| Template | That 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. |
| Construct | A building block in your code. One Python object that stands for one or more resources, such as s3.Bucket. |
| App | Your whole CDK project. It holds one or more stacks. |
| Synth (synthesize) | Run your Python and produce the template. Nothing changes in AWS. |
| Deploy | Send the template to CloudFormation so it creates or updates the real resources. |
| Diff | Show what a deploy would change, without changing anything. |
| Destroy | Delete a stack and its resources. |
Click each box, left to right, to follow your code on its way to AWS.
- Your Python code
- You write classes in .py files that list the resources you want. Nothing here talks to AWS; it is only a description.
s3.Bucket(self, "DataBucket", versioned=True) - Template
- cdk synth runs your Python and writes a text file listing every resource and its settings, into the cdk.out folder. Still nothing has changed in AWS.
cdk synth - CloudFormation
- cdk deploy uploads the template. CloudFormation reads the list, works out the right order, and creates each resource. If one fails, it undoes the others (a rollback).
cdk deploy - A stack
- The finished group of real resources in your AWS account, under one name. cdk diff compares your code against it, and cdk destroy deletes the whole group.
cdk destroy
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
| Word | Plain meaning |
|---|---|
| AWS account | Your private space in AWS, with a 12-digit ID number. Everything you create lives in an account, and the account gets the bill. |
| Sandbox account | An account used only for learning and experiments, with nothing important in it. Use one while learning. |
| Region | A part of the world where AWS has data centers, such as us-west-2 (Oregon). You choose a Region for your resources. |
| Environment | One account plus one Region. It answers "where does this stack go?" |
| Credentials | The 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. |
| Permission | One allowed action, such as "read files from this bucket". |
| Policy | A written list of permissions. |
| Role | A 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 privilege | Giving 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.
| Tool | Minimum version | Check it | Install from |
|---|---|---|---|
| Node.js | 22.x (an active LTS release) | node --version | nodejs.org |
| Python (with pip and virtualenv) | 3.10 | python3 --version | python.org |
| AWS CLI | v2 | aws --version | AWS CLI install guide |
| CDK CLI | latest | cdk --version | npm 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.
| Step | Command | Changes your computer? | Changes your AWS account? |
|---|---|---|---|
| 1 | aws configure / aws sts get-caller-identity | Writes your credentials to ~/.aws/ | No (read-only check) |
| 2 | cdk init app --language python | Creates project files, a git repo and a virtual environment | No |
| 3 | source .venv/bin/activate, pip install | Installs packages inside the project folder only | No |
| 4 | cdk bootstrap | No | Yes: creates a CDKToolkit stack, once per account and Region |
| 5 | cdk ls, cdk synth | Writes 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:
| Part | Meaning |
|---|---|
cdk | The CDK CLI you installed with npm |
init | "Create a new project in the current folder." The folder must be empty. |
app | Which 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 python | Which 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:
Copied the template files (12 files:
app.py,cdk.json,requirements.txt, thehello_cdk/package and a starter test). It named things after your folder:hello-cdkbecomes the Python packagehello_cdkand the classHelloCdkStack. Python names can't contain hyphens, so the hyphen becomes an underscore.Created a git repository and made a first commit called "Initial commit" (only if git is installed). The generated
.gitignorekeeps.venv/andcdk.out/out of git.Created a Python virtual environment in
.venv/: a private copy of Python just for this project.Installed the dependencies from
requirements.txt(aws-cdk-libandconstructs) 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 latercdkcommand how to run your code. That is the link between the CLI and your Python. Itscontextblock holds about 90 "feature flags" that switch on the newest recommended CDK behaviors for new projects. Leave them as they are.app.py: creates theAppand oneHelloCdkStack. It includes two commented-outenv=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):
| Resource | Default name (in your account and Region) | What it's for |
|---|---|---|
| S3 bucket | cdk-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 repository | cdk-hnb659fds-container-assets-<account>-<region> | Holds Docker images if your app builds any. |
| Deploy role | cdk-hnb659fds-deploy-role-... | The CDK CLI assumes it to start each deployment. |
| CloudFormation execution role | cdk-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 role | cdk-hnb659fds-file-publishing-role-... | Used to upload assets to the S3 bucket. |
| Image publishing role | cdk-hnb659fds-image-publishing-role-... | Used to push Docker images to the ECR repository. |
| Lookup role | cdk-hnb659fds-lookup-role-... | Read-only role for lookups such as ec2.Vpc.from_lookup. |
| SSM parameter | /cdk-bootstrap/hnb659fds/version | Records 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.
$ 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.
(.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:
| Step | To undo it | Notes |
|---|---|---|
| Install CDK CLI | npm uninstall -g aws-cdk | |
| 1. Credentials | Access 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 init | rm -rf hello-cdk | Run 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 environment | deactivate. To rebuild it from scratch: rm -rf .venv && python3 -m venv .venv && source .venv/bin/activate && python -m pip install -r requirements.txt | Safe: .venv only holds downloaded packages |
4. cdk bootstrap | See "Removing the bootstrap" below | Only once you're completely finished with CDK in that account and Region |
5. cdk synth | rm -rf cdk.out | Recreated 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.
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.
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 textDelete 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-2This 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-2and run the delete again.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 rmdoesn'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.
>>> 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.
| Type | Example | Typical CDK use |
|---|---|---|
str (text) | "prod" | construct IDs, tag values, names |
int (whole number) | 30 | memory size, retention days |
float (decimal) | 0.5 | thresholds |
bool | True / False | versioned=True, enforce_ssl=True |
None | None | "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.
Click or hover over a box to read about it.
- Python on your computer (shared)
- Without virtual environments, every project installs its packages into this one shared place. Each package can be there in only one version at a time.
- Project A (no virtual environment)
- Project A was written for version 2.100 of the CDK library. It works only while that exact version is the one installed.
- Project B (no virtual environment)
- Project B needs version 2.277. Installing it replaces 2.100 for the whole computer, so Project A stops working. This is called a dependency conflict.
- Python on your computer (left alone)
- With virtual environments, the Python that came with your computer stays clean. Other programs that rely on it are never affected by your projects.
- Project A folder
- A project is just a folder. Its .venv folder sits inside it, so deleting the project folder also removes its packages.
- .venv inside Project A
- A folder holding a private Python and the packages for this one project. cdk init creates it for you. To create one by hand:
python3 -m venv .venv - Project B folder
- A second project keeps a different version of the same package. Neither project can affect the other.
- .venv inside Project B
- A .venv is safe to delete and rebuild at any time, because it only holds downloaded packages:
rm -rf .venv && python3 -m venv .venv && source .venv/bin/activate && python -m pip install -r requirements.txt - 1. Activate
- This changes a setting in this one terminal window only. Other terminal windows are not affected, and nothing is installed or started.
source .venv/bin/activate - 2. Type python or pip
- Activating puts .venv/bin at the front of the list of places the terminal searches for commands. That list is called the PATH.
which python - 3. The private copy runs
- pip install now adds packages inside .venv, and python can import them. This is how your CDK code finds the CDK library.
python -m pip install -r requirements.txt
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.
$ 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
| File | What it does | Do you edit it? |
|---|---|---|
app.py | Creates the App, creates each stack, calls app.synth() | Yes: add stacks and environments here |
hello_cdk/*.py | Stack and construct classes | Yes: most of your work |
cdk.json | The app command plus feature flags | Rarely |
requirements.txt | Packages your app needs | Yes, when you add a library |
tests/ | pytest tests of the generated templates | Yes |
cdk.context.json | Cached results of lookups, such as VPC IDs | No, 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.
Click a box to see the line of Python that creates it and its path in the tree.
- App (root)
- The top of the tree. There is exactly one App, created in app.py. It holds the stacks. Its path is empty because it is the root.
app = cdk.App() - StorageStack (Stack)
- A stack whose parent (scope) is the app. Everything inside it is deployed together. Path in the tree: StorageStack
StorageStack(app, "StorageStack") - ApiStack (Stack)
- A second stack with the same parent. It can be deployed or destroyed without touching StorageStack. Path: ApiStack
ApiStack(app, "ApiStack") - DataBucket (s3.Bucket)
- A construct inside StorageStack. "self" means the stack this line is written in. Path: StorageStack/DataBucket. On synth it becomes an AWS::S3::Bucket plus a bucket policy.
s3.Bucket(self, "DataBucket", enforce_ssl=True) - Handler (lambda_.Function)
- A construct inside ApiStack. Path: ApiStack/Handler. On synth it becomes an AWS::Lambda::Function plus an IAM role.
lambda_.Function(self, "Handler", ...)
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.
| Command | What it does | When to use it |
|---|---|---|
cdk synth | Runs your Python and prints the CloudFormation template | After every change, to see what you built |
cdk diff | Compares your code with what is deployed | Before every deploy; this is your review step |
cdk deploy | Uploads assets and deploys through CloudFormation | When the diff looks right |
cdk destroy | Deletes the stack | When 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.
(.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 wholeAWS::S3::BucketPolicythat denies non-HTTPS requests.auto_delete_objects=Trueadded 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
| Level | What it is | How to spot it | Use it when |
|---|---|---|---|
| L1 ("CFN resources") | Maps 1:1 to a CloudFormation resource, no defaults | Name starts with Cfn, e.g. s3.CfnBucket | No L2 exists yet, or you need a raw CloudFormation property |
| L2 (curated) | One resource with secure defaults and helper methods | Plain name, e.g. s3.Bucket, lambda_.Function | Most of the time: your default choice |
| L3 (patterns) | Several resources wired together for a common job | Usually in a patterns module, e.g. ecs_patterns.ApplicationLoadBalancedFargateService | A 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_assetpoints 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
| Assertion | What 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.
(.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.
| Practice | Why it matters | How, in Python |
|---|---|---|
| Start simple; add complexity only when needed | You can refactor later; don't design for every scenario up front | One stack, L2 constructs, add more when a real need appears |
| Model with constructs, deploy with stacks | Constructs are reusable; stacks are just units of deployment | Feature = a Construct class (section 7); stacks only compose them |
| Configure with props, not environment variables | Env-var lookups tie the code to one machine | Keyword-only props; read os.getenv only at the top of app.py |
| Make decisions at synth time | Python if/for are far more capable than CloudFormation Conditions/Parameters | if config.is_prod: instead of CfnParameter and CfnCondition |
| Use generated names, not physical names | Hardcoded names block a second deployment and break replacements | Omit bucket_name, function_name, table_name; pass bucket.bucket_name |
| Don't change logical IDs of stateful resources | A new logical ID replaces the resource: an empty new bucket or database | Keep construct IDs and nesting stable; test the IDs (section 9) |
| Define removal policies and log retention | Defaults retain data and keep logs forever, which costs money | Set removal_policy on each stateful resource; set log retention |
| Separate stateful from stateless stacks | Destroy and recreate stateless parts without risking data | A storage stack with termination_protection=True (section 8) |
Commit cdk.context.json | Lookups are cached, so every synth gives the same template | git add cdk.context.json |
| Never change AWS during synth | Synth must be side-effect free so CloudFormation can roll back | No boto3 write calls in stack code; use custom resources if needed |
| Let CDK manage roles and security groups | Grants produce minimal, correct permissions | bucket.grant_read(fn); newer releases also offer bucket.grants.read(fn) |
| Model all production stages in code | Every commit yields the same templates for every environment | A config per stage in code (section 8); secrets in Secrets Manager or Parameter Store |
| Unit test your infrastructure | Catches regressions before deploy | pytest + aws_cdk.assertions (section 9) |
| Don't rely on wrapper constructs for compliance | Wrappers can be bypassed | cdk-nag or CloudFormation Guard, plus SCPs and permission boundaries |
| Measure everything | You can't automate deployments you can't observe | L2 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 diffbefore 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-libwith~=inrequirements.txtand 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.
Read
cdk.json. Theappline tells you the entry file (usuallypython3 app.py). Thecontextblock holds feature flags and settings the code may read.Read
app.pytop to bottom. List every stack it creates, theenv(account and Region) each gets, and what is passed between stacks. This is the app's map.Run
cdk lsto confirm the stack names, thencdk synth <StackName>for the one you care about.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).Follow custom constructs. When you see an unfamiliar class like
UploadProcessor(...), find where it's imported and read its__init__. Look forself.xxx =lines to see what it exposes.Trace the connections. Search for
grant_,add_event_,environment=, and constructor arguments that receive another construct. These are the data flows and permissions.Look up anything unfamiliar in the CDK Python API reference. Every prop and method is documented there.
Check the safety settings:
removal_policy, hardcoded names,Cfn(L1) constructs oradd_property_override(escape hatches),NagSuppressionsand their reasons.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.
- Step 1: Find where the program starts (cdk.json): Open cdk.json first. The "app" line is the command that every cdk command runs. It says the program starts in app.py, so that is the next file to open.
- Step 1: Glance at the context block (cdk.json): "context" holds settings the code can read. Here it contains only the feature flags that cdk init wrote. Look for anything custom, such as a "stage" value. There is none, so move on.
- Step 2: app.py, the imports (app.py): The imports show which stack classes exist and which file each one lives in. There is one: HelloCdkStack, in hello_cdk/hello_cdk_stack.py.
- Step 2: app.py, the map of the app (app.py): One App and one stack. In the stack line, "app" is the parent and "HelloCdkStack" is the name the stack will have in AWS. There is no env= setting, so it deploys to whichever account and Region your credentials point to.
- Step 2: app.py, what else happens (app.py): Line 9 puts a Project tag on every resource in the app. Line 11 produces the templates. Nothing else happens here, so the whole app is that single stack.
- Step 3: Confirm the list of stacks (terminal): cdk ls runs the code and prints the stacks it defines. It matches what app.py showed: one stack. In a larger project this list tells you which stack to read first.
- Step 4: Open the stack and skim the frame (hello_cdk/hello_cdk_stack.py): Skim these lines. The imports show which AWS services are used: only S3. Lines 6 to 8 are the same skeleton in every stack. The real content starts after super().__init__.
- Step 4: Each construct, its class and its ID (hello_cdk/hello_cdk_stack.py): s3.Bucket is the class: this creates an S3 bucket. "self" means its parent is this stack. "DataBucket" is its ID, which becomes the logical ID DataBucketE3889A50 in the template. There is no bucket_name, so AWS generates the real name.
- Step 4: Each construct, its settings (hello_cdk/hello_cdk_stack.py): Read the props one by one: no public access, encrypted, HTTPS only, versioning on, and old versions deleted after 30 days. These five lines tell you how the bucket behaves.
- Step 5: Look for custom constructs (hello_cdk/hello_cdk_stack.py): Every class used in this file comes from aws_cdk. There is no import from the project's own folders, so there is no custom construct to open and read.
- Step 6: Trace the connections (hello_cdk/hello_cdk_stack.py): Search for grant_, add_event_ and environment=. There are none, so no other resource is given access to the bucket. The only use of the bucket is here: its generated name is printed after deploy.
- Step 7: Look up what is unfamiliar (hello_cdk/hello_cdk_stack.py): Not sure what noncurrent_version_expiration does? Search for s3.LifecycleRule in the CDK Python API reference. It deletes old versions of a file after the given time.
- Step 8: Check the safety settings (hello_cdk/hello_cdk_stack.py): These two lines decide what happens to data. DESTROY with auto_delete_objects means cdk destroy deletes the bucket and every file in it. Fine for practice, a warning sign in production code.
- Check your reading against the template (terminal): The template is the ground truth. It lists five resources: the bucket, the HTTPS policy (from enforce_ssl), and three helpers (from auto_delete_objects). The last two lines are CDK bookkeeping and create nothing you pay for.
- Step 9: Read the tests (tests/unit/test_hello_cdk_stack.py): Test names show what the author wanted to guarantee: the bucket is versioned and encrypted, public access is blocked, and there is exactly one bucket. Summary of the whole app: one stack holding one private, encrypted, versioned practice bucket.
Python you'll meet in other people's code
| You see | It 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 b | One-line if/else |
Optional[str], str | None | Type 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
Reads an environment variable inside a construct; take
stageas a prop instead.os.environ["STAGE"]crashes withKeyErrorif the variable isn't set.Hardcoded
bucket_namemeans the stack can't be deployed twice and the bucket can't be replaced.s3:*on*grants every S3 action on every bucket in the account. Usebucket.grant_read(...)instead.A hand-built role where a grant on the function's own role would do.
Missing
enforce_ssl=Trueand an explicit removal policy.bucketis a local variable, so callers can't use it; store it asself.bucket.The parameter named
idshadows Python's built-inid(); useconstruct_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
| Command | Purpose |
|---|---|
cdk init app --language python | New project |
source .venv/bin/activate | Turn on the virtual environment |
cdk bootstrap aws://ACCOUNT/REGION | One-time setup per account and Region |
cdk ls | List 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 python | Generate CDK from existing resources |
python -m pytest | Run 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
AWS CDK v2 Developer Guide: concepts and how-tos
CDK Python API reference: every construct, prop and method
Construct Hub: third-party and AWS Solutions constructs
aws-samples/aws-cdk-examples: official sample apps, including a
pythonfolder
Glossary
Short, plain definitions in alphabetical order. The core ideas (stack, template, construct, app, Region, IAM) are explained under "Key ideas in plain language".
| Term | Plain meaning |
|---|---|
| API reference | The official list of every construct and setting, where you look things up |
| ARN | Amazon Resource Name: the full, unique address of one resource in AWS |
| Asset | A file from your computer that CDK uploads during a deploy, such as zipped Lambda code |
| Attribute | A piece of data stored on an object, such as bucket.bucket_name |
| Bootstrap | The one-time setup that gives CDK a storage bucket and permissions in your account |
| Bucket (S3) | A container in AWS for storing files |
| Class | A blueprint in Python for making objects |
| CloudWatch Logs | The AWS service where programs such as Lambda functions write their log messages |
| Construct ID | The name you give a construct (its second argument), unique within its parent |
| Context | Small settings passed to your app, from cdk.json or with -c key=value |
| Cross-stack reference | One stack using a resource that another stack created |
| Custom resource | A helper CDK adds to do a job CloudFormation can't do alone, such as emptying a bucket |
| Dead-letter queue | A second queue that collects messages that kept failing, so they aren't lost |
| Encryption | Scrambling data so only authorized parties can read it |
| Enum | A fixed list of allowed choices, such as s3.BucketEncryption.S3_MANAGED |
| Escape hatch | A way to set a low-level option that the high-level construct doesn't offer |
| Grant | A one-line way to give one resource permission to use another |
| Handler | The function inside your Lambda code that AWS calls |
| L1, L2, L3 | Three levels of construct, from raw and detailed (L1) to ready-made patterns (L3) |
| Lambda function | A small piece of your code that AWS runs on demand, with no server for you to manage |
| Log group | A named place in CloudWatch Logs holding one program's log messages |
| Logical ID | The name CloudFormation uses for a resource inside a stack |
| Method | A function that belongs to an object, such as bucket.grant_read() |
| Object | One thing made from a class |
| Output | A value a stack prints after deploying, such as a generated bucket name |
| Package | A folder of Python code that can be installed or imported |
| Props | The settings you pass to a construct as keyword arguments |
| Queue (SQS) | A waiting line of messages that one program writes and another reads |
| Removal policy | What happens to a resource when it leaves the stack: keep it (RETAIN) or delete it (DESTROY) |
| Rollback | AWS undoing a failed deploy so the stack returns to its last working state |
| Runtime | The language and version a Lambda function runs on, such as Python 3.14 |
| Scope | A construct's parent (its first argument), usually self |
| Stateful / stateless | Holding data you must not lose / holding nothing that can't be rebuilt |
| Token | A placeholder for a value that isn't known until deploy time |
| Traceback | Python's error report, read from the bottom up |
| Virtual environment | A private folder of Python packages for one project |
Sources
Best practices for developing and deploying cloud infrastructure with the AWS CDK
Lambda managed runtimes in public preview: Node.js 26 and Python 3.15
Code in sections 5 through 12 verified with aws-cdk-lib 2.277.0 and cdk-nag 3.0.2 on November 14, 2026.