banner

KuchBhiLearning - A free website to learn and code

This is a good learning site. This contains details of cloud computing, AWS, AWS-CDK, AWS-SDK codes and examples including S3, Redis, lambda, api-gateway, cloudfront, cloudformation.

 AWS CDK Custom Constructs

CDK constructs are cloud components. We use constructs to encapsulate logic, which we can reuse throughout our infrastructure code.

AWS also defines Constructs as they are the basic building blocks of AWS CDK apps. A construct represents a "cloud component" and encapsulates everything AWS Cloud Formation needs to create the component.

Constructs allow us to remove some of the duplication associated with provisioning resources and provide a higher level of abstraction.

In this article we are going to cover as to how to create our own constructs.

When defining our own constructs, we have to follow a specific approach. All constructs extend the Construct class.

Let's take an example of creating an S3 bucket

import * as s3 from 'aws-cdk-lib/aws-s3';
import { Construct } from 'constructs';
import * as cdk from 'aws-cdk-lib';

export class s3BucketConstruct extends Construct {
  public readonly s3Bucket: s3.Bucket;

  public constructor(scope: Construct, id: string) {
    super(scope, id);

    this.s3Bucket = new s3.Bucket(scope, `sample-s3-bucket`, {
      // Block all public access
      blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
      // When stack is deleted, delete this bucket also
      removalPolicy: cdk.RemovalPolicy.DESTROY,
      // Delete contained objects when bucket is deleted
      autoDeleteObjects: true,
    });
  }
}

export class CdkCloudFormationStack extends cdk.Stack {
  constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
    super(scope, id, props);
    const { s3Bucket } = new s3BucketConstruct(this, 'sample-s3-bucket');
  }
}

This is an example custom construct.

Constructs in itself is a huge topic and there are different levels of construct. You can check here



1 comment:

  1. Thank you for writing this. I found this at the right time!

    ReplyDelete

If you have any doubts, Please let me know

Copyright 2022, KuchBhiLearning - A free website to learn and code. All rights Reserved.
| Designed by Yaseen Shariff