The CDK Construct Library for AWS::CloudFront
Project description
Amazon CloudFront Construct Library
---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
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). Constructs to define origins are in the @aws-cdk/aws-cloudfront-origins
module.
Each distribution has a default behavior which applies to all requests to that distribution, and routes requests to a primary origin. Additional behaviors may be specified for an origin with 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 other settings.
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
import aws_cdk.aws_cloudfront_origins as origins
# Creates a distribution for a S3 bucket.
my_bucket = s3.Bucket(self, "myBucket")
cloudfront.Distribution(self, "myDist",
default_behavior=BehaviorOptions(origin=origins.S3Origin(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.
ELBv2 Load Balancer
An Elastic Load Balancing (ELB) v2 load balancer may be used as an origin. In order for a load balancer to serve as an origin, it must be publicly
accessible (internetFacing
is true). Both Application and Network load balancers are supported.
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import aws_cdk.aws_ec2 as ec2
import aws_cdk.aws_elasticloadbalancingv2 as elbv2
vpc = ec2.Vpc(...)
# Create an application load balancer in a VPC. 'internetFacing' must be 'true'
# for CloudFront to access the load balancer and use it as an origin.
lb = elbv2.ApplicationLoadBalancer(self, "LB",
vpc=vpc,
internet_facing=True
)
cloudfront.Distribution(self, "myDist",
default_behavior={"origin": origins.LoadBalancerV2Origin(lb)}
)
From an HTTP endpoint
Origins can also be created from any other HTTP endpoint, given the domain name, and optionally, other origin properties.
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
cloudfront.Distribution(self, "myDist",
default_behavior={"origin": origins.HttpOrigin("www.example.com")}
)
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, and provide one (or more) domain names from the certificate for the distribution.
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. When a certificate is used, the distribution will support HTTPS connections from SNI only and a minimum protocol version of TLSv1.2_2019.
# 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": origins.S3Origin(my_bucket)},
domain_names=["www.example.com"],
certificate=my_certificate
)
However, you can customize the minimum protocol version for the certificate while creating the distribution using minimumProtocolVersion
property.
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
cloudfront.Distribution(self, "myDist",
default_behavior={"origin": origins.S3Origin(my_bucket)},
domain_names=["www.example.com"],
minimum_protocol_version=SecurityPolicyProtocol.TLS_V1_2016
)
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": origins.S3Origin(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 viewer protocol policy 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", origins.S3Origin(my_bucket),
viewer_protocol_policy=ViewerProtocolPolicy.REDIRECT_TO_HTTPS
)
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 = origins.S3Origin(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
}
}
)
Customizing Cache Keys and TTLs with Cache Policies
You can use a cache policy to improve your cache hit ratio by controlling the values (URL query strings, HTTP headers, and cookies) that are included in the cache key, and/or adjusting how long items remain in the cache via the time-to-live (TTL) settings. CloudFront provides some predefined cache policies, known as managed policies, for common use cases. You can use these managed policies, or you can create your own cache policy that’s specific to your needs. See https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html for more details.
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
# Using an existing cache policy
cloudfront.Distribution(self, "myDistManagedPolicy",
default_behavior={
"origin": bucket_origin,
"cache_policy": cloudfront.CachePolicy.CACHING_OPTIMIZED
}
)
# Creating a custom cache policy -- all parameters optional
my_cache_policy = cloudfront.CachePolicy(self, "myCachePolicy",
cache_policy_name="MyPolicy",
comment="A default policy",
default_ttl=Duration.days(2),
min_ttl=Duration.minutes(1),
max_ttl=Duration.days(10),
cookie_behavior=cloudfront.CacheCookieBehavior.all(),
header_behavior=cloudfront.CacheHeaderBehavior.allow_list("X-CustomHeader"),
query_string_behavior=cloudfront.CacheQueryStringBehavior.deny_list("username"),
enable_accept_encoding_gzip=True,
enable_accept_encoding_brotli=True
)
cloudfront.Distribution(self, "myDistCustomPolicy",
default_behavior={
"origin": bucket_origin,
"cache_policy": my_cache_policy
}
)
Customizing Origin Requests with Origin Request Policies
When CloudFront makes a request to an origin, the URL path, request body (if present), and a few standard headers are included. Other information from the viewer request, such as URL query strings, HTTP headers, and cookies, is not included in the origin request by default. You can use an origin request policy to control the information that’s included in an origin request. CloudFront provides some predefined origin request policies, known as managed policies, for common use cases. You can use these managed policies, or you can create your own origin request policy that’s specific to your needs. See https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-origin-requests.html for more details.
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
# Using an existing origin request policy
cloudfront.Distribution(self, "myDistManagedPolicy",
default_behavior={
"origin": bucket_origin,
"origin_request_policy": cloudfront.OriginRequestPolicy.CORS_S3_ORIGIN
}
)
# Creating a custom origin request policy -- all parameters optional
my_origin_request_policy = cloudfront.OriginRequestPolicy(stack, "OriginRequestPolicy",
origin_request_policy_name="MyPolicy",
comment="A default policy",
cookie_behavior=cloudfront.OriginRequestCookieBehavior.none(),
header_behavior=cloudfront.OriginRequestHeaderBehavior.all("CloudFront-Is-Android-Viewer"),
query_string_behavior=cloudfront.OriginRequestQueryStringBehavior.allow_list("username")
)
cloudfront.Distribution(self, "myDistCustomPolicy",
default_behavior={
"origin": bucket_origin,
"cache_policy": my_cache_policy,
"origin_request_policy": my_origin_request_policy
}
)
Lambda@Edge
Lambda@Edge is an extension of AWS Lambda, a compute service that lets you execute functions that customize the content that CloudFront delivers. You can author Node.js or Python functions in the US East (N. Virginia) region, and then execute them in AWS locations globally that are closer to the viewer, without provisioning or managing servers. Lambda@Edge functions are associated with a specific behavior and event type. Lambda@Edge can be used to rewrite URLs, alter responses based on headers or cookies, or authorize requests based on headers or authorization tokens.
The following shows a Lambda@Edge function added to the default behavior and triggered on every request:
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
my_func = cloudfront.experimental.EdgeFunction(self, "MyFunction",
runtime=lambda_.Runtime.NODEJS_10_X,
handler="index.handler",
code=lambda_.Code.from_asset(path.join(__dirname, "lambda-handler"))
)
cloudfront.Distribution(self, "myDist",
default_behavior={
"origin": origins.S3Origin(my_bucket),
"edge_lambdas": [{
"function_version": my_func.current_version,
"event_type": cloudfront.LambdaEdgeEventType.VIEWER_REQUEST
}
]
}
)
Note: Lambda@Edge functions must be created in the
us-east-1
region, regardless of the region of the CloudFront distribution and stack. To make it easier to request functions for Lambda@Edge, theEdgeFunction
construct can be used. TheEdgeFunction
construct will automatically request a function inus-east-1
, regardless of the region of the current stack.EdgeFunction
has the same interface asFunction
and can be created and used interchangably. Please note that usingEdgeFunction
requires that theus-east-1
region has been bootstrapped. See https://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html for more about bootstrapping regions.
If the stack is in us-east-1
, a "normal" lambda.Function
can be used instead of an EdgeFunction
.
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
my_func = lambda_.Function(self, "MyFunction",
runtime=lambda_.Runtime.NODEJS_10_X,
handler="index.handler",
code=lambda_.Code.from_asset(path.join(__dirname, "lambda-handler"))
)
If the stack is not in us-east-1
, and you need references from different applications on the same account,
you can also set a specific stack ID for each Lamba@Edge.
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
my_func1 = cloudfront.experimental.EdgeFunction(self, "MyFunction1",
runtime=lambda_.Runtime.NODEJS_10_X,
handler="index.handler",
code=lambda_.Code.from_asset(path.join(__dirname, "lambda-handler1")),
stack_id="edge-lambda-stack-id-1"
)
my_func2 = cloudfront.experimental.EdgeFunction(self, "MyFunction2",
runtime=lambda_.Runtime.NODEJS_10_X,
handler="index.handler",
code=lambda_.Code.from_asset(path.join(__dirname, "lambda-handler2")),
stack_id="edge-lambda-stack-id-2"
)
Lambda@Edge functions can also be associated with additional behaviors, either at or after Distribution creation time.
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
# assigning at Distribution creation
my_origin = origins.S3Origin(my_bucket)
cloudfront.Distribution(self, "myDist",
default_behavior={"origin": my_origin},
additional_behaviors={
"images/*": {
"origin": my_origin,
"edge_lambdas": [{
"function_version": my_func.current_version,
"event_type": cloudfront.LambdaEdgeEventType.ORIGIN_REQUEST,
"include_body": True
}
]
}
}
)
# assigning after creation
my_distribution.add_behavior("images/*", my_origin,
edge_lambdas=[{
"function_version": my_func.current_version,
"event_type": cloudfront.LambdaEdgeEventType.VIEWER_RESPONSE
}
]
)
Adding an existing Lambda@Edge function created in a different stack to a CloudFront distribution.
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
function_version = lambda_.Version.from_version_arn(self, "Version", "arn:aws:lambda:us-east-1:123456789012:function:functionName:1")
cloudfront.Distribution(self, "distro",
default_behavior={
"origin": origins.S3Origin(s3_bucket),
"edge_lambdas": [{
"function_version": function_version,
"event_type": cloudfront.LambdaEdgeEventType.VIEWER_REQUEST
}
]
}
)
Logging
You can configure CloudFront to create log files that contain detailed information about every user request that CloudFront receives. The logs can go to either an existing bucket, or a bucket will be created for you.
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
# Simplest form - creates a new bucket and logs to it.
cloudfront.Distribution(self, "myDist",
default_behavior={"origin": origins.HttpOrigin("www.example.com")},
enable_logging=True
)
# You can optionally log to a specific bucket, configure whether cookies are logged, and give the log files a prefix.
cloudfront.Distribution(self, "myDist",
default_behavior={"origin": origins.HttpOrigin("www.example.com")},
enable_logging=True, # Optional, this is implied if loggingBucket is specified
logging_bucket=s3.Bucket(self, "LoggingBucket"),
logging_file_prefix="distribution-access-logs/",
logging_includes_cookies=True
)
Importing Distributions
Existing distributions can be imported as well; note that like most imported constructs, an imported distribution cannot be modified. However, it can be used as a reference for other higher-level constructs.
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
distribution = cloudfront.Distribution.from_distribution_attributes(scope, "ImportedDist",
domain_name="d111111abcdef8.cloudfront.net",
distribution_id="012345ABCDEF"
)
CloudFrontWebDistribution API
The
CloudFrontWebDistribution
construct is the original construct written for working with CloudFront distributions. Users are encouraged to use the newerDistribution
instead, as it has a simpler interface and receives new features faster.
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
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)
}
]
)
Origin Fallback
In case the origin source is not available and answers with one of the specified status code the failover origin source will be used.
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
CloudFrontWebDistribution(stack, "ADistribution",
origin_configs=[{
"s3_origin_source": {
"s3_bucket_source": s3.Bucket.from_bucket_name(stack, "aBucket", "myoriginbucket"),
"origin_path": "/",
"origin_headers": {
"my_header": "42"
}
},
"failover_s3_origin_source": {
"s3_bucket_source": s3.Bucket.from_bucket_name(stack, "aBucketFallback", "myoriginbucketfallback"),
"origin_path": "/somwhere",
"origin_headers": {
"my_header2": "21"
}
},
"failover_criteria_status_codes": [FailoverStatusCode.INTERNAL_SERVER_ERROR],
"behaviors": [{
"is_default_behavior": True
}
]
}
]
)
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
Built Distribution
File details
Details for the file aws-cdk.aws-cloudfront-1.83.0.tar.gz
.
File metadata
- Download URL: aws-cdk.aws-cloudfront-1.83.0.tar.gz
- Upload date:
- Size: 284.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.3.0 pkginfo/1.6.1 requests/2.25.1 setuptools/39.0.1 requests-toolbelt/0.9.1 tqdm/4.55.1 CPython/3.6.5
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | a29fea7b2ea428aa22024c18a2e9ad48f8990afc8282980f17fb4cb45a0658d3 |
|
MD5 | a75d91648a0ad3c01e0bcdca3ca7795c |
|
BLAKE2b-256 | 9cb8e19216b6277bf21e08818fc3d747974c90d27815a4787d48c1c3335daccc |
File details
Details for the file aws_cdk.aws_cloudfront-1.83.0-py3-none-any.whl
.
File metadata
- Download URL: aws_cdk.aws_cloudfront-1.83.0-py3-none-any.whl
- Upload date:
- Size: 276.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.3.0 pkginfo/1.6.1 requests/2.25.1 setuptools/39.0.1 requests-toolbelt/0.9.1 tqdm/4.55.1 CPython/3.6.5
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 65ef900d25cac612458c6d368963d6decbe994db57bd5c6279c3b319f4d050ed |
|
MD5 | 21508941c9d39377087a8f088ace74f1 |
|
BLAKE2b-256 | 731afd2ad3127b7388ced0d7dc42e426cf312e9d6f77c1958160f1fa16f16978 |