Skip to main content

CDK Constructs for AWS CloudFront

Project description

Amazon CloudFront Construct Library

---
Features Stability
CFN Resources Stable
Higher level constructs for Distribution Experimental
Higher level constructs for CloudFrontWebDistribution Stable

CFN Resources: All classes with the Cfn prefix in this module (CFN Resources) are always stable and safe to use.

Experimental: Higher level constructs in this module that are marked as experimental are under active development. They are subject to non-backward compatible changes or removal in any future version. These are not subject to the Semantic Versioning model and breaking changes will be announced in the release notes. This means that while you may use them, you may need to update your source code when upgrading to a newer version of this package.

Stable: Higher level constructs in this module that are marked stable will not undergo any breaking changes. They will strictly follow the Semantic Versioning model.


Amazon CloudFront is a web service that speeds up distribution of your static and dynamic web content, such as .html, .css, .js, and image files, to your users. CloudFront delivers your content through a worldwide network of data centers called edge locations. When a user requests content that you're serving with CloudFront, the user is routed to the edge location that provides the lowest latency, so that content is delivered with the best possible performance.

Distribution API - Experimental

cdk-constructs: Experimental

The Distribution API is currently being built to replace the existing CloudFrontWebDistribution API. The Distribution API is optimized for the most common use cases of CloudFront distributions (e.g., single origin and behavior, few customizations) while still providing the ability for more advanced use cases. The API focuses on simplicity for the common use cases, and convenience methods for creating the behaviors and origins necessary for more complex use cases.

Creating a distribution

CloudFront distributions deliver your content from one or more origins; an origin is the location where you store the original version of your content. Origins can be created from S3 buckets or a custom origin (HTTP server). Each distribution has a default behavior which applies to all requests to that distribution, and routes requests to a primary origin.

From an S3 Bucket

An S3 bucket can be added as an origin. If the bucket is configured as a website endpoint, the distribution can use S3 redirects and S3 custom error documents.

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import aws_cdk.aws_cloudfront as cloudfront

# Creates a distribution for a S3 bucket.
my_bucket = s3.Bucket(self, "myBucket")
cloudfront.Distribution(self, "myDist",
    default_behavior=BehaviorOptions(origin=cloudfront.Origin.from_bucket(my_bucket))
)

The above will treat the bucket differently based on if IBucket.isWebsite is set or not. If the bucket is configured as a website, the bucket is treated as an HTTP origin, and the built-in S3 redirects and error pages can be used. Otherwise, the bucket is handled as a bucket origin and CloudFront's redirect and error handling will be used. In the latter case, the Origin wil create an origin access identity and grant it access to the underlying bucket. This can be used in conjunction with a bucket that is not public to require that your users access your content using CloudFront URLs and not S3 URLs directly.

Domain Names and Certificates

When you create a distribution, CloudFront assigns a domain name for the distribution, for example: d111111abcdef8.cloudfront.net; this value can be retrieved from distribution.distributionDomainName. CloudFront distributions use a default certificate (*.cloudfront.net) to support HTTPS by default. If you want to use your own domain name, such as www.example.com, you must associate a certificate with your distribution that contains your domain name. The certificate must be present in the AWS Certificate Manager (ACM) service in the US East (N. Virginia) region; the certificate may either be created by ACM, or created elsewhere and imported into ACM.

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
my_certificate = acm.DnsValidatedCertificate(self, "mySiteCert",
    domain_name="www.example.com",
    hosted_zone=hosted_zone
)
cloudfront.Distribution(self, "myDist",
    default_behavior={"origin": cloudfront.Origin.from_bucket(my_bucket)},
    certificate=my_certificate
)

Multiple Behaviors & Origins

Each distribution has a default behavior which applies to all requests to that distribution; additional behaviors may be specified for a given URL path pattern. Behaviors allow routing with multiple origins, controlling which HTTP methods to support, whether to require users to use HTTPS, and what query strings or cookies to forward to your origin, among others.

The properties of the default behavior can be adjusted as part of the distribution creation. The following example shows configuring the HTTP methods and viewer protocol policy of the cache.

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
my_web_distribution = cloudfront.Distribution(self, "myDist",
    default_behavior={
        "origin": cloudfront.Origin.from_bucket(my_bucket),
        "allowed_methods": AllowedMethods.ALLOW_ALL,
        "viewer_protocol_policy": ViewerProtocolPolicy.REDIRECT_TO_HTTPS
    }
)

Additional behaviors can be specified at creation, or added after the initial creation. Each additional behavior is associated with an origin, and enable customization for a specific set of resources based on a URL path pattern. For example, we can add a behavior to myWebDistribution to override the default time-to-live (TTL) for all of the images.

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
my_web_distribution.add_behavior("/images/*.jpg", cloudfront.Origin.from_bucket(my_other_bucket),
    viewer_protocol_policy=ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
    default_ttl=cdk.Duration.days(7)
)

These behaviors can also be specified at distribution creation time.

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
bucket_origin = cloudfront.Origin.from_bucket(my_bucket)
cloudfront.Distribution(self, "myDist",
    default_behavior={
        "origin": bucket_origin,
        "allowed_methods": AllowedMethods.ALLOW_ALL,
        "viewer_protocol_policy": ViewerProtocolPolicy.REDIRECT_TO_HTTPS
    },
    additional_behaviors={
        "/images/*.jpg": {
            "origin": bucket_origin,
            "viewer_protocol_policy": ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
            "default_ttl": cdk.Duration.days(7)
        }
    }
)

CloudFrontWebDistribution API - Stable

cdk-constructs: Stable

A CloudFront construct - for setting up the AWS CDN with ease!

Example usage:

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
source_bucket = Bucket(self, "Bucket")

distribution = CloudFrontWebDistribution(self, "MyDistribution",
    origin_configs=[{
        "s3_origin_source": {
            "s3_bucket_source": source_bucket
        },
        "behaviors": [{"is_default_behavior": True}]
    }
    ]
)

Viewer certificate

By default, CloudFront Web Distributions will answer HTTPS requests with CloudFront's default certificate, only containing the distribution domainName (e.g. d111111abcdef8.cloudfront.net). You can customize the viewer certificate property to provide a custom certificate and/or list of domain name aliases to fit your needs.

See Using Alternate Domain Names and HTTPS in the CloudFront User Guide.

Default certificate

You can customize the default certificate aliases. This is intended to be used in combination with CNAME records in your DNS zone.

Example:

# Example automatically generated. See https://github.com/aws/jsii/issues/826
s3_bucket_source = s3.Bucket(self, "Bucket")

distribution = cloudfront.CloudFrontWebDistribution(self, "AnAmazingWebsiteProbably",
    origin_configs=[SourceConfiguration(
        s3_origin_source=S3OriginConfig(s3_bucket_source=s3_bucket_source),
        behaviors=[Behavior(is_default_behavior=True)]
    )],
    viewer_certificate=cloudfront.ViewerCertificate.from_cloud_front_default_certificate("www.example.com")
)

ACM certificate

You can change the default certificate by one stored AWS Certificate Manager, or ACM. Those certificate can either be generated by AWS, or purchased by another CA imported into ACM.

For more information, see the aws-certificatemanager module documentation or Importing Certificates into AWS Certificate Manager in the AWS Certificate Manager User Guide.

Example:

# Example automatically generated. See https://github.com/aws/jsii/issues/826
s3_bucket_source = s3.Bucket(self, "Bucket")

certificate = certificatemanager.Certificate(self, "Certificate",
    domain_name="example.com",
    subject_alternative_names=["*.example.com"]
)

distribution = cloudfront.CloudFrontWebDistribution(self, "AnAmazingWebsiteProbably",
    origin_configs=[SourceConfiguration(
        s3_origin_source=S3OriginConfig(s3_bucket_source=s3_bucket_source),
        behaviors=[Behavior(is_default_behavior=True)]
    )],
    viewer_certificate=cloudfront.ViewerCertificate.from_acm_certificate(certificate,
        aliases=["example.com", "www.example.com"],
        security_policy=cloudfront.SecurityPolicyProtocol.TLS_V1, # default
        ssl_method=cloudfront.SSLMethod.SNI
    )
)

IAM certificate

You can also import a certificate into the IAM certificate store.

See Importing an SSL/TLS Certificate in the CloudFront User Guide.

Example:

# Example automatically generated. See https://github.com/aws/jsii/issues/826
s3_bucket_source = s3.Bucket(self, "Bucket")

distribution = cloudfront.CloudFrontWebDistribution(self, "AnAmazingWebsiteProbably",
    origin_configs=[SourceConfiguration(
        s3_origin_source=S3OriginConfig(s3_bucket_source=s3_bucket_source),
        behaviors=[Behavior(is_default_behavior=True)]
    )],
    viewer_certificate=cloudfront.ViewerCertificate.from_iam_certificate("certificateId",
        aliases=["example.com"],
        security_policy=cloudfront.SecurityPolicyProtocol.SSL_V3, # default
        ssl_method=cloudfront.SSLMethod.SNI
    )
)

Restrictions

CloudFront supports adding restrictions to your distribution.

See Restricting the Geographic Distribution of Your Content in the CloudFront User Guide.

Example:

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
cloudfront.CloudFrontWebDistribution(stack, "MyDistribution",
    # ...
    geo_restriction=GeoRestriction.whitelist("US", "UK")
)

Connection behaviors between CloudFront and your origin

CloudFront provides you even more control over the connection behaviors between CloudFront and your origin. You can now configure the number of connection attempts CloudFront will make to your origin and the origin connection timeout for each attempt.

See Origin Connection Attempts

See Origin Connection Timeout

Example usage:

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
distribution = CloudFrontWebDistribution(self, "MyDistribution",
    origin_configs=[{...,
        "connection_attempts": 3,
        "connection_timeout": cdk.Duration.seconds(10)
    }
    ]
)

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

aws-cdk.aws-cloudfront-1.53.0.tar.gz (211.1 kB view details)

Uploaded Source

Built Distribution

aws_cdk.aws_cloudfront-1.53.0-py3-none-any.whl (209.4 kB view details)

Uploaded Python 3

File details

Details for the file aws-cdk.aws-cloudfront-1.53.0.tar.gz.

File metadata

  • Download URL: aws-cdk.aws-cloudfront-1.53.0.tar.gz
  • Upload date:
  • Size: 211.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.5.0.1 requests/2.24.0 setuptools/39.0.1 requests-toolbelt/0.9.1 tqdm/4.48.0 CPython/3.6.5

File hashes

Hashes for aws-cdk.aws-cloudfront-1.53.0.tar.gz
Algorithm Hash digest
SHA256 c83daa1f8375d83a94c0db186d600ba767f46d28838ccd2d404d47ecd36ea352
MD5 2ed1eea4b73af3cb75d01d5da1b8bf5e
BLAKE2b-256 e284e21a541c58f479c4818dd513a9ad404c25aeb020d31d8353ac14d6ed0e06

See more details on using hashes here.

File details

Details for the file aws_cdk.aws_cloudfront-1.53.0-py3-none-any.whl.

File metadata

  • Download URL: aws_cdk.aws_cloudfront-1.53.0-py3-none-any.whl
  • Upload date:
  • Size: 209.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.5.0.1 requests/2.24.0 setuptools/39.0.1 requests-toolbelt/0.9.1 tqdm/4.48.0 CPython/3.6.5

File hashes

Hashes for aws_cdk.aws_cloudfront-1.53.0-py3-none-any.whl
Algorithm Hash digest
SHA256 f1c4aac02863e41f4a34b9b8ce1632c145e9d01cfd28ff4cfe074700846596cb
MD5 bba4ba3091c9799d0033b143a3cfbbde
BLAKE2b-256 062703ff29541fde599791c411739926cbf1112422c2aca4754032af1d4c8c8e

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page