DEV Community

Cover image for AWS-CDK Custom constructs
Yaseen
Yaseen

Posted on

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.

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,
    });
  }
}
Enter fullscreen mode Exit fullscreen mode

This is how we can create custom construct.
You can also refer https://kuchbhilearning.blogspot.com/2022/09/aws-cdk-custom-constructs.html

Top comments (0)