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.

 Add Cloudfront Behavior using AWS-CDK

Cloudfront has various features which help us to build our applications.
One of the feature is origin and behaviors. We can specific the routing based on certain path pattern and navigate to api or s3. The default behavior will be *.  

Now the question is how to do this through CDK?

Let's take an example of creating an origin and behavior for S3 bucket.

In this example we will create 1 origin and 2 behaviors and just for example both the behavior's will be pointing to S3 bucket.  

Let's dive into the code - 
import * as s3 from 'aws-cdk-lib/aws-s3';
import * as cloudFront from 'aws-cdk-lib/aws-cloudfront';
import * as cloudFrontOrigins from 'aws-cdk-lib/aws-cloudfront-origins';
 
const s3BucketWeb = new s3.Bucket(stack, `s3-web`, {
    // 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
  });

  let s3origin = new cloudFrontOrigins.S3Origin(s3BucketWeb);

  const cloudFrontDistribution = new cloudFront.Distribution(stack, `cloudfront-example`, {
    // Default path pointing to S3 Web Bucket where static content resides
    defaultBehavior: {
      // Point to S3 Web Bucket as origin
      origin: s3origin,
      // HTTP requests will be redirected to HTTPS
      viewerProtocolPolicy: cloudFront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
      // Only allow GET, HEAD, OPTIONS methods
      allowedMethods: cloudFront.AllowedMethods.ALLOW_GET_HEAD_OPTIONS,
      // Cache GET, HEAD, OPTIONS
      cachedMethods: cloudFront.CachedMethods.CACHE_GET_HEAD_OPTIONS,
    },
  });


  cloudFrontDistribution.addBehavior('/test', s3origin, {
    viewerProtocolPolicy: cloudFront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
    // Allow all methods for REST API endpoints
    allowedMethods: cloudFront.AllowedMethods.ALLOW_ALL,
    cachePolicy: cloudFront.CachePolicy.CACHING_DISABLED,
  });
In this example we have not deep dived into the cloudfront and it's additional behavior's.

This is strictly restricted to show how we can create origins and attach that origin to cloudfront behavior.

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