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.

Deep level understanding of AWS CDK constructs


Constructs are the basic building blocks of AWS CDK apps. A construct represents a "cloud component" and encapsulates everything AWS CloudFormation needs to create the component.

A construct can represent a single AWS resource, such as an Amazon Simple Storage Service (Amazon S3) bucket, or it can be a higher-level abstraction consisting of multiple related AWS resources. Examples of such components include a worker queue with its associated compute capacity, or a scheduled job with monitoring resources and a dashboard.

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

A construct can provision one or more AWS resources and serves a specific purpose. For instance, we can have a construct that provisions a S3 bucket or we can have a construct which provisions an Rest API for attaching our lambda's.

Initialization

Constructs are implemented in classes that extend the Construct base class. You define a construct by instantiating the class. All constructs take three parameters when they are initialized:

scope — The construct's parent or owner, either a stack or another construct, which determines its place in the construct tree. You should usually pass this (or self in Python), which represents the current object, for the scope.

id — An identifier that must be unique within this scope. The identifier serves as a namespace for everything that's defined within the current construct and is used to generate unique identifiers such as resource names and AWS CloudFormation logical IDs.

props — A set of properties or keyword arguments, depending upon the language, that define the construct's initial configuration. In most cases, constructs provide sensible defaults, and if all props elements are optional, you can leave out the props parameter completely.

There are 3 levels of Constructs we can use in CDK. The different construct levels represent different abstraction levels. From Level 1 (the least opinionated, with least assumptions) to Level 3 (the most opinionated, with most defaults and logic in place).

Cfn Resources (Level 1)

Cfn (Level 1) resources are 1x1 mapping with how you would provision the resource using CloudFormation.

L1 constructs are exactly the resources defined by AWS CloudFormation, no more, no less.

We only use Cfn resources as a last resort - in case we need the flexibility. They are low level and don't provide any opinionated defaults or any of the glue logic for service to service interactions.

An example of a Cfn Resource is a CfnBucket/CfnReplicationGroup.
import * as s3 from 'aws-cdk-lib/aws-s3';
import * as cdk from 'aws-cdk-lib';

export class CdkExampleStack extends cdk.Stack {
  constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
    super(scope, id, props);
    // Using the CfnBucket
    const bucket = new s3.CfnBucket(this, 'sample-bucket');
  }
}

// Initializing the application
const app = new cdk.App();

new CdkExampleStack(app, `cdk-constructs-cloud-formation-stack-dev`, {
  stackName: `cdk-constructs-cloud-formation-stack-dev`,
  env: { region: 'us-east-1' },
});

Level 2 Constructs

Level 2 Constructs are higher level constructs, defined in the AWS Constructs library. They provide sane defaults and helper methods for service to service interactions.

The higher level of abstraction they provide, makes it easier to focus on the bigger picture and not as much on the details of the resources we have to provision.

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

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

    // using Level 2 Bucket construct
    const bucket = new s3.Bucket(this, 'sample-bucket');

    // using level 2 Function construct
    const helloFunction = new lambda.Function(this, 'hello-function', {
      runtime: lambda.Runtime.NODEJS_16_X,
      handler: 'handler',
      code: lambda.Code.fromAsset(path.join(__dirname, 'hello-handler')),
    });

    // using utility methods exposed by the Level 2 Bucket Construct
    bucket.grantPut(helloFunction);
    bucket.grantPutAcl(helloFunction);
  }
}


With just 2 lines of code we created a policy that follows the best practices of least privilege and grants our lambda permissions for the s3:PutObject and s3:PutObjectAcl actions.

Level 3 Construct

Level 3 constructs provide an even higher level of abstraction. These are even more specific and opinionated than level 2 constructs and serve a very specific use case.
import * as apigateway from 'aws-cdk-lib/aws-apigateway';
import * as cdk from 'aws-cdk-lib';
import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs';

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

    const lambdaFunction = new NodejsFunction(this, 'hello-function', {});

    // use the Level 3 LambdaRestApi construct
    const lambdaRestApi = new apigateway.LambdaRestApi(this, 'hello-lambda-rest-api', {
      handler: lambdaFunction,
    });
  }
}
Using the LambdaRestAPI level 3 construct allows us to create a Rest API with a lambda proxy integration.

Notice how as the levels of constructs get higher, more assumptions are made as to how these constructs are going to be used, which allows us to provide interfaces with sane defaults for very specific use cases.

You can also write your own Level 3 constructs, i.e. an Endpoint construct, which creates a Lambda function and assign it to apigateway with certain format which is readable and re-usable.

If you want to read how to create a custom construct check here


No comments:

Post a Comment

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