AWS CDK CloudFront Construct Library

1.204.0 · active · verified Fri Apr 17

The `aws-cdk-aws-cloudfront` package provides CDK constructs for defining AWS CloudFront distributions and related resources using Python. It's part of the AWS Cloud Development Kit (CDK) v1 ecosystem, enabling infrastructure-as-code for CloudFront. AWS CDK is actively maintained by Amazon Web Services, with frequent minor releases and security updates, often on a weekly or bi-weekly cadence. The current version covered here is 1.204.0.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a basic AWS CloudFront distribution in CDK v1. It configures an S3 bucket as the origin and uses an Origin Access Identity (OAI) for secure access. The distribution is set to redirect HTTP requests to HTTPS and specifies `index.html` as the default root object. Remember to configure your AWS credentials and `CDK_DEFAULT_ACCOUNT`/`CDK_DEFAULT_REGION` environment variables.

import os
from aws_cdk import (
    core as cdk,
    aws_s3 as s3,
    aws_cloudfront as cloudfront,
    aws_cloudfront_origins as origins,
)

class CloudFrontDistroStack(cdk.Stack):
    def __init__(self, scope: cdk.App, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        # Create an S3 bucket to serve as the origin for CloudFront
        bucket = s3.Bucket(
            self, "WebsiteBucket",
            versioned=False,
            removal_policy=cdk.RemovalPolicy.DESTROY,
            auto_delete_objects=True # Be cautious with auto_delete_objects in production
        )

        # Create an Origin Access Identity (OAI) for CloudFront to securely access S3
        # In AWS CDK v2, Origin Access Control (OAC) is the recommended alternative.
        oai = cloudfront.OriginAccessIdentity(
            self, "OAI",
            comment="Allows CloudFront to access S3 bucket"
        )
        # Grant the OAI read permissions to the S3 bucket
        bucket.grant_read(oai)

        # Create a CloudFront Distribution
        cloudfront.Distribution(
            self, "MyDistribution",
            default_behavior=cloudfront.BehaviorOptions(
                origin=origins.S3Origin(bucket, origin_access_identity=oai),
                viewer_protocol_policy=cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS
            ),
            default_root_object="index.html" # Assumes an index.html file in your S3 bucket
        )

app = cdk.App()
CloudFrontDistroStack(app, "MyCloudFrontDistroStack",
                      env=cdk.Environment(
                          account=os.environ.get('CDK_DEFAULT_ACCOUNT'),
                          region=os.environ.get('CDK_DEFAULT_REGION')
                      )
)
app.synth()

view raw JSON →