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 *.
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 -
In this example we have not deep dived into the cloudfront and it's additional behavior's.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 accessblockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,// When stack is deleted, delete this bucket alsoremovalPolicy: cdk.RemovalPolicy.DESTROY,// Delete contained objects when bucket is deletedautoDeleteObjects: 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 residesdefaultBehavior: {// Point to S3 Web Bucket as originorigin: s3origin,// HTTP requests will be redirected to HTTPSviewerProtocolPolicy: cloudFront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,// Only allow GET, HEAD, OPTIONS methodsallowedMethods: cloudFront.AllowedMethods.ALLOW_GET_HEAD_OPTIONS,// Cache GET, HEAD, OPTIONScachedMethods: cloudFront.CachedMethods.CACHE_GET_HEAD_OPTIONS,},});cloudFrontDistribution.addBehavior('/test', s3origin, {viewerProtocolPolicy: cloudFront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,// Allow all methods for REST API endpointsallowedMethods: cloudFront.AllowedMethods.ALLOW_ALL,cachePolicy: cloudFront.CachePolicy.CACHING_DISABLED,});
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