Sub topic 4
Apps, stacks and the construct tree
This chapter assumes you can create a CDK project and run cdk synth, and that you know what a CloudFormation stack is. Here you will learn how the CDK organizes your code into a tree. That tree decides what gets deployed together, how resources are named, and how identifiers stay stable between deployments.
Everything is a construct
A construct is a class from the constructs library. Every object you create in a CDK program is a construct: the app, each stack, each bucket, and each Lambda function. A construct is always created with three arguments:
scope: the parent construct that will contain it.id: a string that names it within that parent.props: an optional object of settings.
Because each construct has a parent, the constructs form a tree. The root of the tree is the App. Its children are normally stacks. The children of a stack are resources and higher-level constructs, and those can contain further constructs.
The App
App is the root construct. It has no parent, so you create it with no scope. Its job is to hold stacks and, during synthesis, to write the cloud assembly. The cloud assembly is the cdk.out directory that contains one CloudFormation template per stack, plus asset files and a manifest.
An app is not deployed itself. Only the stacks inside it are deployed.
The Stack
A Stack is the unit of deployment. One CDK stack becomes one CloudFormation stack. Everything inside it is created, updated, and rolled back together.
A stack also has an environment: the account and region it deploys to. Chapter-level details on environments come later. For now, note that each stack in an app can target a different environment.
Because a stack maps to a CloudFormation stack, it inherits CloudFormation limits. A stack can hold at most 500 resources. Splitting resources across stacks is a design choice about blast radius, deployment order, and ownership, not only about size.
A two-stack app
This program defines two stacks and prints every path in the tree.
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as s3 from 'aws-cdk-lib/aws-s3';
import * as sqs from 'aws-cdk-lib/aws-sqs';
class StorageStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
new s3.Bucket(this, 'Uploads', { versioned: true });
}
}
class QueueStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
new sqs.Queue(this, 'Jobs');
}
}
const app = new cdk.App();
new StorageStack(app, 'Storage');
new QueueStack(app, 'Queue');
for (const node of app.node.findAll()) {
console.log(node.node.path === '' ? '(app)' : node.node.path);
}Running cdk synth prints paths such as these, along with other framework-created nodes:
(app)
Storage
Storage/Uploads
Storage/Uploads/Resource
Queue
Queue/Jobs
Queue/Jobs/ResourceEvery construct exposes this metadata through its node property. The properties you will use most are node.id, node.path, node.scope, node.children, and node.defaultChild. The method node.findAll() walks the whole subtree, and node.tryFindChild(id) returns a direct child or undefined.
The same inspection works in Python:
from aws_cdk import App, Stack
from aws_cdk import aws_s3 as s3
from constructs import Construct
class StorageStack(Stack):
def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)
s3.Bucket(self, "Uploads", versioned=True)
app = App()
StorageStack(app, "Storage")
for construct in app.node.find_all():
print(construct.node.path or "(app)")
app.synth()The Resource child
Why does Storage/Uploads/Resource exist? An L2 construct such as s3.Bucket is a wrapper. Inside it, it creates an L1 construct, CfnBucket, which maps directly to the CloudFormation resource AWS::S3::Bucket. By convention that L1 child is named Resource (or Default in some constructs).
You can reach it with node.defaultChild. This is the usual escape hatch for setting a property the L2 does not expose:
const bucket = new s3.Bucket(this, 'Uploads');
const cfnBucket = bucket.node.defaultChild as s3.CfnBucket;
cfnBucket.addPropertyOverride('ObjectLockEnabled', true);Identifiers and logical IDs
Two rules about IDs follow from the tree.
- An
idmust be unique among its siblings, not across the whole app. Two stacks can each contain a construct calledUploads. Creating two constructs with the sameidunder the same scope throws an error at construction time. - The CloudFormation logical ID is computed from the construct path. The CDK joins the path segments, removes
ResourceandDefault, and appends an 8-character hash of the path. The bucket above gets a logical ID likeUploadsXXXXXXXX, where the suffix is a hash.
The hash keeps logical IDs unique while still allowing readable names. The physical name of the resource, such as the real bucket name, is a separate value. CloudFormation generates it unless you set it yourself.
Choosing what goes in a stack
Resources that share a lifecycle belong together. Common splits are:
- Stateful and stateless resources apart, such as a database in one stack and application code in another.
- One stack per environment or per team boundary.
- Separate stacks when a resource group changes at a very different pace.
Stack boundaries have a cost. When a resource in one stack uses a resource in another, the CDK creates a CloudFormation export and import behind the scenes. That ties the two stacks together, so you cannot freely delete or change the exported value. Cross-stack references get their own chapter.
You can also set an order explicitly with stackB.addDependency(stackA). The CDK adds dependencies for you when it detects references.
Stages: grouping stacks
A Stage is a construct between the app and its stacks. It holds a set of stacks that are deployed together as one unit, such as a whole "Prod" copy of your system. Stacks created inside a stage are synthesized into their own nested cloud assembly. Stages are the building block that CDK Pipelines uses later in this tutorial.
Common mistakes
- Passing the wrong scope. Writing
new s3.Bucket(app, 'Uploads')instead ofthisplaces the bucket directly in the app, where it belongs to no stack. Synthesis fails with an error that the construct is not in a stack. - Doing work in the constructor that depends on deploy-time values. The tree is built at synthesis, before anything is deployed. Values that CloudFormation resolves later are handled by tokens, covered in a later chapter.
- Using the same stack ID in two places. The stack ID is also the CloudFormation stack name, so it must be unique per environment.
Exercise
A stack contains new s3.Bucket(this, 'Data'). You later rename the ID to 'DataBucket' and deploy without checking. What does CloudFormation do, and how can you detect it beforehand?
Show answer
The path changes from Stack/Data to Stack/DataBucket, so the logical ID changes. CloudFormation sees a new resource and an removed one: it creates a new bucket and then deletes the old one, subject to the old bucket's removal policy. Running cdk diff before deploying shows the old resource being removed and the new one being added.
Exercise
Which node would you use to set a CloudFormation property that the L2 s3.Bucket does not expose, and how do you get it from the bucket?
Show answer
Use the L1 child, CfnBucket. Get it with bucket.node.defaultChild, cast it to s3.CfnBucket, and then call addPropertyOverride or set its properties directly.