3
votes

I'm new to CDK and confused about the difference between a Construct and a Stack. With CDK, we can define reusable cloud components known as Construct, and we can further compose these together into a Stack or Apps. See the diagram from AWS website below,

enter image description here

However, I've seen class where a construct is created by extending the Construct base class, and also class where a Stack is created by extending the Stack base class. Both child classes can be used later to create the main stack. For example, see the code below, I can create a Construct or a Stack called HitCounter class that creates the same set of resources and use them the same way in the main Stack. So what's the difference between using a Stack or a Construct?

import * as cdk from '@aws-cdk/core';

export class HitCounterConstruct extends cdk.Construct {} // imagine this construct creates a bunch of related resources

export class HitCounterStack extends cdk.Stack {} // imagine this stack creates the same resources as the construct class above

// In main stack file App.ts

new HitCounterConstruct(cdk.App, "construct");
new HitCounterStack(cdk.App, "stack");

please correct me if I made any mistake in code. Thanks in advance :)

2

2 Answers

4
votes

Stack represent CF template in CDK terms. While Construct represents AWS resources which you want to create, like Lambda function, S3 bucket, Api gateway, etc.

Or if you want, Stack is your text file when we write bare CF template, like yaml or json, Constructs is resources defined in this file.

In your case, if you try deploy own HitCounterStack it will be an empty cf template with no resources, if you don't add any constructs to HitCounterStack.

To render cf template by cdk need follow this structure: Stack -> Constructs, like file->resources, but on top of it should be also defined App which is also extends base class Construct, so final right schema for cdk code should be:

App -> Stack -> Constructs.

1
votes

Stack is a CloudFormation concept. It’s deployed as a unit.

Construct is a CDK OOP class that just holds similar things together for separation of concerns and has no effect on CloudFormation result.