amazon-web-servicesaws-cloudformationaws-cdk

The difference between a Stack and Construct in AWS CDK


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 :)


Solution

  • Stack represents 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 CF template, in yaml or json, Constructs are resources defined in this file.

    In your case, if you try to deploy HitCounterStack without any Constructs, it will be an empty cf template with no resources.

    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 also extends base class Construct, so final right schema for CDK code should be:

    App -> Stack -> Constructs.

    Also need to know that Constructs represented by 3 levels. 1-st level Construct mapped to AWS resources one-to-one. One-to-one means Construct represent single AWS resource. 1st level Construct name starts with Cfn.

    2nd level Constructs also maped 1-1 to CloudFormation resources but

    higher-level abstraction through an intuitive intent-based API 1

    And 3rd levels Constructs more high level. So when you define 2nd level Construct in CDK template will be created several AWS resources, when you define 3rd level Construct – even more resources will be created.

    This is for abstract routine procedures. Like create S3 bucket website, Lambda app and so on.