Select your cookie preferences

We use cookies and similar tools to enhance your experience, provide our services, deliver relevant advertising, and make improvements. Approved third parties also use these tools to help us deliver advertising and provide certain site features.

CloudFront to Lambda@Edge

Created with SnapCloudFrontLambda@Edge

CloudFront to Lambda@Edge

This pattern deploys an Amazon Cloudfront distribution, a Lambda@Edge function and a Amazon S3 Bucket and demonstrates how to generate content at edge.

from aws_cdk import (
    Stack,
    CfnOutput,
    aws_cloudfront as cloudfront,
    aws_cloudfront_origins as origins,
    aws_s3 as s3,
    aws_lambda as _lambda
)
from constructs import Construct

class CloudfrontLambdaEdgeCdkPythonStack(Stack):

    def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        lambda_edge = _lambda.Function(self, 'LambdaEdge',
            runtime = _lambda.Runtime.PYTHON_3_7,
            handler = 'index.handler',
            code = _lambda.Code.from_asset('lambda'),
        )

        #create an S3 bucket used as origin for Cloudfront, not used but origin is a required field
        hosting_bucket = s3.Bucket(self, "MyHostingBucket")

        my_distribution = cloudfront.Distribution(self, "MyDistribution",
            default_behavior=cloudfront.BehaviorOptions(
                origin=origins.S3Origin(hosting_bucket),
                edge_lambdas=[cloudfront.EdgeLambda(
                    function_version=lambda_edge.current_version,
                    event_type=cloudfront.LambdaEdgeEventType.ORIGIN_REQUEST
                )
                ]
            ),
            comment = 'Dynamic content generation using Lambda@Edge'
        )


        CfnOutput(self, "DomainName",
            value = my_distribution.domain_name,
            export_name = 'DomainName',
            description = 'CloudFront Domain Name')

< Back to all patterns


GitHub icon Visit the GitHub repo for this pattern.

Download

git clone https://github.com/aws-samples/serverless-patterns/ cd serverless-patterns/cloudfront-lambda-edge-cdk-python

Deploy

cdk deploy


Testing

See the GitHub repo for testing instructions.

Cleanup

1. In the source folder, from the command line enter:
cdk destroy
2. See additional notes in the repo.

Additional resources

Corneliu Croitoru

Presented by Corneliu Croitoru

Developer at heart, in 2018 joined AWS as a Solution Architect and since 2021 building, jointly with customers, the most exciting and innovative prototypes on AWS.

Follow on LinkedIn