AWS-CDK App Hierarchy and Key Concepts

1. AWS CDK App

Definition:

AWS-CDK App hierarchy is the starting point for defining cloud resources using AWS CDK. This application is a project written in one of the supported languages, such as TypeScript or Python, and uses the AWS CDK library to describe the desired AWS infrastructure.

Example:

Let’s consider a simple AWS CDK App written in TypeScript:

TypeScript
import * as cdk from 'aws-cdk-lib';
import { Stack } from './stack';

const app = new cdk.App();
new Stack(app, 'MyFirstStack');

In this example, we initiate an AWS CDK App and define a new stack named. MyFirstStack.


2. AWS-CDK App Hierarchy: Stacks

Definition:

Stacks in AWS CDK act as a logical unit of AWS resources. Each stack is deployable and directly maps to an AWS CloudFormation stack. Within a single AWS CDK App, you can have multiple stacks, each with its specific AWS resources like Amazon S3 buckets or Lambda functions.

Example:

Given below is a TypeScript example of defining a stack that consists of an Amazon S3 bucket:

TypeScript
import * as cdk from 'aws-cdk-lib';
import * as s3 from 'aws-cdk-lib/aws-s3';

export class MyS3Stack extends cdk.Stack {
    constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
        super(scope, id, props);

        new s3.Bucket(this, 'MyFirstBucket', {
            removalPolicy: cdk.RemovalPolicy.DESTROY,
        });
    }
}

Here, we create an S3 bucket within the stack. The bucket is defined to be destroyed if the stack is deleted (using. RemovalPolicy.DESTROY).


3. AWS-CDK App Hierarchy: Constructs

Constructs are the atomic building blocks in AWS CDK. They are objects that encapsulate one or more AWS resources.

a. L1 (Layer 1) – AWS CloudFormation-only

Definition:

L1 constructs map 1:1 with AWS CloudFormation resource types. These are low-level constructs and are generated automatically based on AWS CloudFormation Resource Specification.

Example:

To create an Amazon S3 bucket using an L1 construct:

TypeScript
import * as cdk from 'aws-cdk-lib';
const bucket = new cdk.aws_s3.CfnBucket(this, 'MyFirstL1Bucket');

b. L2 (Layer 2) – Curated

Definition:

L2 constructs are higher-level constructs provided by AWS CDK. They encapsulate L1 constructs, embedding best practices, and offer convenient methods to set properties, methods, and defaults.

Example:

Here’s how to create an S3 bucket using an L2 construct:

TypeScript
import * as s3 from 'aws-cdk-lib/aws-s3';
const bucket = new s3.Bucket(this, 'MyFirstL2Bucket');

c. L3 (Layer 3) – Patterns

Definition:

L3 constructs, also known as patterns, are solutions for common cloud design patterns. They bundle multiple L1 and L2 constructs to provide a holistic solution for specific use cases.

Example:

For instance, the aws-cdk-lib might offer a pattern for creating a serverless website. This L3 construct would bundle an S3 bucket (for web hosting), a CloudFront distribution (for content delivery), and perhaps even Lambda@Edge functions for dynamic content. The user can deploy this entire solution with a single L3 construct, adjusting only a few parameters.

TypeScript
import * as patterns from 'aws-cdk-lib/patterns';
const website = new patterns.ServerlessWebApp(this, 'MyWebApp', { /* ... properties ... */ });

In essence, the AWS CDK offers an object-oriented framework to define cloud resources, spanning from atomic L1 constructs to full-blown architectural patterns in L3 constructs. This layered approach allows developers to choose the right abstraction level for their needs.

AWS-CDK App Hierarchy

The AWS CDK hierarchy primarily consists of three levels: Apps, Stacks, and Constructs. Let’s delve into each level:

1. App:

  • Definition: The topmost level in the hierarchy is the App. It acts as the root container for your AWS infrastructure project. It’s the central unit from where your AWS infrastructure deployment begins. An App can consist of one or more Stacks.
  • Purpose: Organizing multiple stacks, especially in larger projects where resources might be split across different CloudFormation stacks for modularity and manageability.
  • Example:typescript
TypeScript
import * as cdk from 'aws-cdk-lib';

const app = new cdk.App();

2. Stack:

  • Definition: Immediately nested within an App are Stacks. Stacks correspond directly to AWS CloudFormation stacks, meaning when a Stack is synthesized, it gets translated into a CloudFormation template. They are deployable units that contain a collection of related AWS resources.
  • Purpose: Encapsulating related AWS resources into a single, deployable unit. Also, managing AWS limits, as CloudFormation has a resource limit per stack. Splitting infrastructure across stacks allows for complex applications to be described and managed.
  • Example:typescript
TypeScript
import * as cdk from 'aws-cdk-lib';

class MyStack extends cdk.Stack {
    constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
        super(scope, id, props);
        // Define AWS resources here...
    }
}

new MyStack(app, 'MyFirstStack');

3. Construct:

  • Definition: The most granular level in the hierarchy is Constructs. They are the basic building blocks in the AWS CDK. Constructs can represent a single resource (like an Amazon S3 bucket) or a higher-level component composed of several AWS resources. They exist at different levels, such as L1 (low-level CloudFormation mappings), L2 (AWS-curated constructs with sensible defaults), and L3 (patterns).
  • Purpose: Defining and encapsulating AWS resources. Allows for reuse, composition, and sharing of infrastructure patterns.
  • Example:typescript
TypeScript
import * as s3 from 'aws-cdk-lib/aws-s3';

class MyStack extends cdk.Stack {
    constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
        super(scope, id, props);

        // L2 Construct for an S3 Bucket
        new s3.Bucket(this, 'MyBucket');
    }
}

Relationships and Structure:

  • An App can contain multiple Stacks.
  • A Stack can contain multiple Constructs.
  • Constructs can also contain other constructs, allowing for a tree-like structure. This provides a powerful composition mechanism, enabling complex cloud resources to be built from simpler building blocks.

In summary, the AWS CDK app hierarchy provides a structured and organized way to define and manage AWS resources. By utilizing Apps, Stacks, and Constructs, developers can define AWS infrastructure in a modular and reusable way, leveraging the benefits of object-oriented design.

Now explain the heirarchy when using multiple stacks and multiple constructs.ChatGPT

Elsewhere On TurboGeek:  How to Create an AWS-CDK EC2 Instance

When working with more complex AWS CDK applications, it’s common to leverage multiple stacks and multiple constructs. This approach is beneficial for managing, scaling, and modularizing your infrastructure configurations.

Hierarchical Structure with Multiple Stacks and Constructs:

1. App:

  • Definition: Still at the top level, it serves as the central unit from which your AWS infrastructure deployment begins.
  • Multiple Stacks: An App can be visualized as a container that holds multiple stacks. These stacks can represent different functional areas or environments of your application (e.g., networking, database, frontend, dev environment, prod environment).typescript
TypeScript
const app = new cdk.App();
new NetworkStack(app, 'NetworkStack');
new DatabaseStack(app, 'DatabaseStack');
new FrontendStack(app, 'FrontendStack');

2. Stack:

  • Multiple Constructs: Each stack, while being a distinct unit, can contain numerous constructs. These constructs can range from simple resources like an S3 bucket to more complex configurations like a VPC with subnets and security groups.typescript
TypeScript
class NetworkStack extends cdk.Stack {
    constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
        super(scope, id, props);
        
        // Using multiple L2 constructs within this stack
        new ec2.Vpc(this, 'CustomVPC');
        new ec2.SecurityGroup(this, 'CustomSecurityGroup', { vpc: ... });
    }
}

class DatabaseStack extends cdk.Stack {
    constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
        super(scope, id, props);
        
        new rds.DatabaseInstance(this, 'DBInstance', { ... });
    }
}

3. Construct:

  • Composed Constructs: Constructs can be nested or composed, meaning a higher-level construct can be made up of several lower-level constructs. For instance, an L3 construct can combine multiple L2 constructs to represent a more complex setup.typescript
TypeScript
class WebAppWithDatabase extends cdk.Construct {
    constructor(scope: cdk.Construct, id: string) {
        super(scope, id);
        
        // Combine multiple L2 constructs to create a higher-level construct
        const vpc = new ec2.Vpc(this, 'CustomVPC');
        const db = new rds.DatabaseInstance(this, 'DBInstance', { vpc: vpc, ... });
        const webApp = new ecs.FargateService(this, 'WebApp', { vpc: vpc, ... });
    }
}

Benefits of Multiple Stacks and Constructs:

  1. Modularity: Breaking your infrastructure into separate stacks and constructs allows you to manage and evolve different parts of your system independently.
  2. Environment Isolation: By using separate stacks for different environments (e.g., development, staging, production), you can ensure isolation between them, reducing potential risks.
  3. Scalability: As your application grows, having a hierarchical structure with multiple stacks and constructs enables easier scalability, as you can add or modify specific parts without affecting the entire system.
  4. Reusability: Constructs, especially at the L2 and L3 levels, can be shared across multiple stacks or even multiple applications, promoting the DRY (Don’t Repeat Yourself) principle.
  5. Manageability: By dividing infrastructure into logical segments, it becomes much easier to manage, monitor, and debug.

In summary, when dealing with larger projects or more complex infrastructure setups, using multiple stacks and constructs in AWS CDK can streamline the development process, provide better organizational clarity, and offer more granular control over your AWS resources.

Richard.Bailey

Richard Bailey, a seasoned tech enthusiast, combines a passion for innovation with a knack for simplifying complex concepts. With over a decade in the industry, he's pioneered transformative solutions, blending creativity with technical prowess. An avid writer, Richard's articles resonate with readers, offering insightful perspectives that bridge the gap between technology and everyday life. His commitment to excellence and tireless pursuit of knowledge continues to inspire and shape the tech landscape.

You may also like...

4 Responses

  1. 23/08/2023

    […] approach offers a clean, programmatic way to define cloud resources, making it easier to manage, scale, and replicate environments. By harnessing the power of AWS […]

  2. 29/08/2023

    […] constructs, whether from the standard library or custom-made, have three […]

  3. 29/01/2024

    […] code is defining an AWS CDK stack to create an Amazon Virtual Private Cloud (VPC) with IPv6 support and a custom VPC class to create and configure its […]

  4. 06/02/2024

    […] Most users in AWS have multiple VPCs in their environment, sometimes spanning more than one account, so it’s not very common to have all of your resources in a single VPC, in a single account. A VPC is an isolated network, and resources can only communicate from inside each VPC. So, what do you do when you want your AWS resources to communicate with each other? That’s where a VPC Peering Connection comes into play – and best of all you can create and manage it with CDK! […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Translate ยป