Distribution L2 construct
A CloudFront distribution with associated origin(s) and caching behavior(s).
Example
// Creates a distribution from a Network Load Balancer
declare const vpc: ec2.Vpc;
// Create a network load balancer in a VPC. 'internetFacing' can be 'false'.
const nlb = new elbv2.NetworkLoadBalancer(this, 'NLB', {
vpc,
internetFacing: false,
vpcSubnets: { subnetType: ec2.SubnetType.PRIVATE_ISOLATED },
securityGroups: [new ec2.SecurityGroup(this, 'NLB-SG', { vpc })],
});
new cloudfront.Distribution(this, 'myDist', {
defaultBehavior: { origin: origins.VpcOrigin.withNetworkLoadBalancer(nlb) },
});
# Creates a distribution from a Network Load Balancer
# vpc: ec2.Vpc
# Create a network load balancer in a VPC. 'internetFacing' can be 'false'.
nlb = elbv2.NetworkLoadBalancer(self, "NLB",
vpc=vpc,
internet_facing=False,
vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PRIVATE_ISOLATED),
security_groups=[ec2.SecurityGroup(self, "NLB-SG", vpc=vpc)]
)
cloudfront.Distribution(self, "myDist",
default_behavior=cloudfront.BehaviorOptions(origin=origins.VpcOrigin.with_network_load_balancer(nlb))
)
// Creates a distribution from a Network Load Balancer
Vpc vpc;
// Create a network load balancer in a VPC. 'internetFacing' can be 'false'.
NetworkLoadBalancer nlb = NetworkLoadBalancer.Builder.create(this, "NLB")
.vpc(vpc)
.internetFacing(false)
.vpcSubnets(SubnetSelection.builder().subnetType(SubnetType.PRIVATE_ISOLATED).build())
.securityGroups(List.of(SecurityGroup.Builder.create(this, "NLB-SG").vpc(vpc).build()))
.build();
Distribution.Builder.create(this, "myDist")
.defaultBehavior(BehaviorOptions.builder().origin(VpcOrigin.withNetworkLoadBalancer(nlb)).build())
.build();
// Install: dotnet add package Amazon.CDK.Lib
// Creates a distribution from a Network Load Balancer
Vpc vpc;
// Create a network load balancer in a VPC. 'internetFacing' can be 'false'.
var nlb = new NetworkLoadBalancer(this, "NLB", new NetworkLoadBalancerProps {
Vpc = vpc,
InternetFacing = false,
VpcSubnets = new SubnetSelection { SubnetType = SubnetType.PRIVATE_ISOLATED },
SecurityGroups = new [] { new SecurityGroup(this, "NLB-SG", new SecurityGroupProps { Vpc = vpc }) }
});
new Distribution(this, "myDist", new DistributionProps {
DefaultBehavior = new BehaviorOptions { Origin = VpcOrigin.WithNetworkLoadBalancer(nlb) }
});
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
// Creates a distribution from a Network Load Balancer
var vpc Vpc
// Create a network load balancer in a VPC. 'internetFacing' can be 'false'.
nlb := elbv2.NewNetworkLoadBalancer(this, jsii.String("NLB"), &NetworkLoadBalancerProps{
Vpc: Vpc,
InternetFacing: jsii.Boolean(false),
VpcSubnets: &SubnetSelection{
SubnetType: ec2.SubnetType_PRIVATE_ISOLATED,
},
SecurityGroups: []ISecurityGroup{
ec2.NewSecurityGroup(this, jsii.String("NLB-SG"), &SecurityGroupProps{
Vpc: *Vpc,
}),
},
})
cloudfront.NewDistribution(this, jsii.String("myDist"), &DistributionProps{
DefaultBehavior: &BehaviorOptions{
Origin: origins.VpcOrigin_WithNetworkLoadBalancer(nlb),
},
})
Initializer
new Distribution(scope: Construct, id: string, props: DistributionProps)
Distribution(scope: Construct, id: str, props: DistributionProps)
new Distribution(Construct scope, String id, DistributionProps props)
new Distribution(Construct scope, string id, DistributionProps props)
NewDistribution(Scope Construct, Id *string, Props DistributionProps)
Construct Props
additionalBehaviorsoptional{ [key: string]: BehaviorOptions }additional_behaviorsoptionaltyping.Mapping[str, BehaviorOptions]additionalBehaviorsoptionalMap<String, BehaviorOptions>AdditionalBehaviorsoptionalIDictionary<string, BehaviorOptions>AdditionalBehaviorsoptional*map[string]BehaviorOptions#Default: no additional behaviors are added.
certificateoptionalICertificateRefcertificateoptionalICertificateRefcertificateoptionalICertificateRefCertificateoptionalICertificateRefCertificateoptionalICertificateRef#Default: the CloudFront wildcard certificate (*.cloudfront.net) will be used.
The certificate must be located in N. Virginia (us-east-1).
commentoptionalstringcommentoptionalstrcommentoptionalStringCommentoptionalstringCommentoptional*string#Default: no comment
defaultBehaviorBehaviorOptionsdefault_behaviorBehaviorOptionsdefaultBehaviorBehaviorOptionsDefaultBehaviorBehaviorOptionsDefaultBehaviorBehaviorOptionsrequired#defaultRootObjectoptionalstringdefault_root_objectoptionalstrdefaultRootObjectoptionalStringDefaultRootObjectoptionalstringDefaultRootObjectoptional*string#Default: no default root object
domainNamesoptionalstring[]domain_namesoptionaltyping.List[str]domainNamesoptionalList<String>DomainNamesoptionalstring[]DomainNamesoptional*[]*string#Default: The distribution will only support the default generated name (e.g., d111111abcdef8.cloudfront.net)
notes
If you want to use your own domain name, such as www.example.com, instead of the cloudfront.net domain name, you can add an alternate domain name to your distribution. If you attach a certificate to the distribution, you should add (at least one of) the domain names of the certificate to this list.
When you want to move a domain name between distributions, you can associate a certificate without specifying any domain names. For more information, see the Moving an alternate domain name to a different distribution section in the README.
enabledoptionalbooleanenabledoptionalboolenabledoptionalBooleanEnabledoptionalboolEnabledoptional*bool= true#enableIpv6optionalbooleanenable_ipv6optionalboolenableIpv6optionalBooleanEnableIpv6optionalboolEnableIpv6optional*bool= true#If you specify false, CloudFront responds to IPv6 DNS requests with the DNS response code NOERROR and with no IP addresses. This allows viewers to submit a second request, for an IPv4 address for your distribution.
enableLoggingoptionalbooleanenable_loggingoptionalboolenableLoggingoptionalBooleanEnableLoggingoptionalboolEnableLoggingoptional*bool#Default: false, unless logBucket is specified.
errorResponsesoptionalErrorResponse[]error_responsesoptionaltyping.List[ErrorResponse]errorResponsesoptionalList<ErrorResponse>ErrorResponsesoptionalErrorResponse[]ErrorResponsesoptional*[]ErrorResponse#Default: No custom error responses.
geoRestrictionoptionalGeoRestrictiongeo_restrictionoptionalGeoRestrictiongeoRestrictionoptionalGeoRestrictionGeoRestrictionoptionalGeoRestrictionGeoRestrictionoptionalGeoRestriction#Default: No geographic restrictions
httpVersionoptionalHttpVersionhttp_versionoptionalHttpVersionhttpVersionoptionalHttpVersionHttpVersionoptionalHttpVersionHttpVersionoptionalHttpVersion= HttpVersion.HTTP2#For viewers and CloudFront to use HTTP/2, viewers must support TLS 1.2 or later, and must support Server Name Indication (SNI). For viewers and CloudFront to use HTTP/3, viewers must support TLS 1.3 and Server Name Indication (SNI).
logBucketoptionalIBucketlog_bucketoptionalIBucketlogBucketoptionalIBucketLogBucketoptionalIBucketLogBucketoptionalIBucket#Default: A bucket is created if enableLogging is true
Make sure to set objectOwnership to s3.ObjectOwnership.OBJECT_WRITER in your custom bucket.
logFilePrefixoptionalstringlog_file_prefixoptionalstrlogFilePrefixoptionalStringLogFilePrefixoptionalstringLogFilePrefixoptional*string#Default: no prefix
logIncludesCookiesoptionalbooleanlog_includes_cookiesoptionalboollogIncludesCookiesoptionalBooleanLogIncludesCookiesoptionalboolLogIncludesCookiesoptional*bool= false#minimumProtocolVersionoptionalSecurityPolicyProtocolminimum_protocol_versionoptionalSecurityPolicyProtocolminimumProtocolVersionoptionalSecurityPolicyProtocolMinimumProtocolVersionoptionalSecurityPolicyProtocolMinimumProtocolVersionoptionalSecurityPolicyProtocol#Default: SecurityPolicyProtocol.TLS_V1_2_2021 if the '@aws-cdk/aws-cloudfront:defaultSecurityPolicyTLSv1.2_2021' feature flag is set; otherwise, SecurityPolicyProtocol.TLS_V1_2_2019.
CloudFront serves your objects only to browsers or devices that support at least the SSL version that you specify.
priceClassoptionalPriceClassprice_classoptionalPriceClasspriceClassoptionalPriceClassPriceClassoptionalPriceClassPriceClassoptionalPriceClass= PriceClass.PRICE_CLASS_ALL#notes
If you specify PriceClass_All, CloudFront responds to requests for your objects from all CloudFront edge locations. If you specify a price class other than PriceClass_All, CloudFront serves your objects from the CloudFront edge location that has the lowest latency among the edge locations in your price class.
publishAdditionalMetricsoptionalbooleanpublish_additional_metricsoptionalboolpublishAdditionalMetricsoptionalBooleanPublishAdditionalMetricsoptionalboolPublishAdditionalMetricsoptional*bool= false#sslSupportMethodoptionalSSLMethodssl_support_methodoptionalSSLMethodsslSupportMethodoptionalSSLMethodSslSupportMethodoptionalSSLMethodSslSupportMethodoptionalSSLMethod= SSLMethod.SNI#notes
Server Name Indication (SNI) - is an extension to the TLS computer networking protocol by which a client indicates which hostname it is attempting to connect to at the start of the handshaking process. This allows a server to present multiple certificates on the same IP address and TCP port number and hence allows multiple secure (HTTPS) websites (or any other service over TLS) to be served by the same IP address without requiring all those sites to use the same certificate.
CloudFront can use SNI to host multiple distributions on the same IP - which a large majority of clients will support.
If your clients cannot support SNI however - CloudFront can use dedicated IPs for your distribution - but there is a prorated monthly charge for using this feature. By default, we use SNI - but you can optionally enable dedicated IPs (VIP).
See the CloudFront SSL for more details about pricing : https://aws.amazon.com/cloudfront/custom-ssl-domains/
webAclIdoptionalstringweb_acl_idoptionalstrwebAclIdoptionalStringWebAclIdoptionalstringWebAclIdoptional*string#Default: No AWS Web Application Firewall web access control list (web ACL).
notes
To specify a web ACL created using the latest version of AWS WAF, use the ACL ARN, for example arn:aws:wafv2:us-east-1:123456789012:global/webacl/ExampleWebACL/473e64fd-f30b-4765-81a0-62ad96dd167a. To specify a web ACL created using AWS WAF Classic, use the ACL ID, for example 473e64fd-f30b-4765-81a0-62ad96dd167a.
Properties
distributionArnstringdistribution_arnstrdistributionArnStringDistributionArnstringDistributionArn*stringrequired#distributionDomainNamestringdistribution_domain_namestrdistributionDomainNameStringDistributionDomainNamestringDistributionDomainName*stringrequired#distributionIdstringdistribution_idstrdistributionIdStringDistributionIdstringDistributionId*stringrequired#distributionRefDistributionReferencedistribution_refDistributionReferencedistributionRefDistributionReferenceDistributionRefDistributionReferenceDistributionRefDistributionReferencerequired#envResourceEnvironmentenvResourceEnvironmentenvResourceEnvironmentEnvResourceEnvironmentEnvResourceEnvironmentrequired#notes
For resources that are created and managed in a Stack (those created by creating new class instances like new Role(), new Bucket(), etc.), this is always the same as the environment of the stack they belong to.
For referenced resources (those obtained from referencing methods like Role.fromRoleArn(), Bucket.fromBucketName(), etc.), they might be different than the stack they were imported into.
grantsDistributionGrantsgrantsDistributionGrantsgrantsDistributionGrantsGrantsDistributionGrantsGrantsDistributionGrantsrequired#PROPERTY_INJECTION_IDstringproperty_injection_idstrPROPERTY_INJECTION_IDStringPROPERTY_INJECTION_IDstringPROPERTY_INJECTION_ID*stringrequiredstatic#Methods
addBehavior(pathPattern: string, origin: IOrigin, behaviorOptions?: AddBehaviorOptions): voiddef add_behavior(self, path_pattern: str, origin: IOrigin, behavior_options: typing.Optional[AddBehaviorOptions] = None) -> Nonepublic void addBehavior(String pathPattern, IOrigin origin, AddBehaviorOptions behaviorOptions)public void AddBehavior(string pathPattern, IOrigin origin, AddBehaviorOptions? behaviorOptions = null)func AddBehavior(PathPattern *string, Origin IOrigin, BehaviorOptions AddBehaviorOptions)#3 parameters
Parameters
pathPatternpath_patternpathPatternpathPatternPathPattern— the path pattern (e.g., 'images/*') that specifies which requests to apply the behavior to.originoriginoriginoriginOrigin— the origin to use for this behavior.behaviorOptionsbehavior_optionsbehaviorOptionsbehaviorOptionsBehaviorOptions— the options for the behavior at this path.
applyCrossStackReferenceStrength(strength: ReferenceStrength): voiddef apply_cross_stack_reference_strength(self, strength: ReferenceStrength) -> Nonepublic void applyCrossStackReferenceStrength(ReferenceStrength strength)public void ApplyCrossStackReferenceStrength(ReferenceStrength strength)func ApplyCrossStackReferenceStrength(Strength ReferenceStrength)#notes · 1 parameter
When set, any cross-stack reference to this resource will use the specified mechanism instead of the global default determined by the @aws-cdk/core:defaultCrossStackReferences context key. This is useful for selectively weakening specific references to avoid the "deadly embrace" problem without changing the app-wide default.
Parameters
strengthstrengthstrengthstrengthStrength— - The reference strength to use for this resource.
applyRemovalPolicy(policy: RemovalPolicy): voiddef apply_removal_policy(self, policy: RemovalPolicy) -> Nonepublic void applyRemovalPolicy(RemovalPolicy policy)public void ApplyRemovalPolicy(RemovalPolicy policy)func ApplyRemovalPolicy(Policy RemovalPolicy)#notes
The Removal Policy controls what happens to this resource when it stops being managed by CloudFormation, either because you've removed it from the CDK application or because you've made a change that requires the resource to be replaced.
The resource can be deleted (RemovalPolicy.DESTROY), or left in your AWS account for data recovery and cleanup later (RemovalPolicy.RETAIN).
attachWebAclId(webAclId: string): voiddef attach_web_acl_id(self, web_acl_id: str) -> Nonepublic void attachWebAclId(String webAclId)public void AttachWebAclId(string webAclId)func AttachWebAclId(WebAclId *string)#WebACL must be in the us-east-1 region
1 parameter
Parameters
webAclIdweb_acl_idwebAclIdwebAclIdWebAclId— The WAF WebACL to associate with this distribution.
fromDistributionAttributes(scope: Construct, id: string, attrs: DistributionAttributes): IDistribution@staticmethod def from_distribution_attributes(scope: Construct, id: str, attrs: DistributionAttributes) -> IDistributionpublic static IDistribution fromDistributionAttributes(Construct scope, String id, DistributionAttributes attrs)public static IDistribution FromDistributionAttributes(Construct scope, string id, DistributionAttributes attrs)func FromDistributionAttributes(Scope Construct, Id *string, Attrs DistributionAttributes) IDistributionstatic#grant(identity: IGrantable, ...actions: string[]): Grantdef grant(self, identity: IGrantable, actions: str) -> Grantpublic Grant grant(IGrantable identity, String actions)public Grant Grant(IGrantable identity, string actions)func Grant(Identity IGrantable, Actions *string) Grant#[disable-awslint:no-grants]
2 parameters
Parameters
identityidentityidentityidentityIdentity— The principal.actionsactionsactionsactionsActions— The set of actions to allow (i.e. "cloudfront:ListInvalidations").
grantCreateInvalidation(identity: IGrantable): Grantdef grant_create_invalidation(self, identity: IGrantable) -> Grantpublic Grant grantCreateInvalidation(IGrantable identity)public Grant GrantCreateInvalidation(IGrantable identity)func GrantCreateInvalidation(Identity IGrantable) Grant#[disable-awslint:no-grants]
1 parameter
Parameters
identityidentityidentityidentityIdentity— The principal.
isConstruct(x: any): boolean@staticmethod def is_construct(x: Any) -> boolpublic static Boolean isConstruct(Object x)public static bool IsConstruct(object x)func IsConstruct(X interface{}) *boolstatic#notes · 1 parameter · returns
Use this method instead of instanceof to properly detect Construct instances, even when the construct library is symlinked.
Explanation: in JavaScript, multiple copies of the constructs library on disk are seen as independent, completely different libraries. As a consequence, the class Construct in each copy of the constructs library is seen as a different class, and an instance of one class will not test as instanceof the other class. npm install will not create installations like this, but users may manually symlink construct libraries together or use a monorepo tool: in those cases, multiple copies of the constructs library can be accidentally installed, and instanceof will behave unpredictably. It is safest to avoid using instanceof, and using this type-testing method instead.
Parameters
xxxxX— Any object.
Returns: true if x is an object created from a class which extends Construct.
isOwnedResource(construct: IConstruct): boolean@staticmethod def is_owned_resource(construct: IConstruct) -> boolpublic static Boolean isOwnedResource(IConstruct construct)public static bool IsOwnedResource(IConstruct construct)func IsOwnedResource(Construct IConstruct) *boolstatic#isResource(construct: IConstruct): boolean@staticmethod def is_resource(construct: IConstruct) -> boolpublic static Boolean isResource(IConstruct construct)public static bool IsResource(IConstruct construct)func IsResource(Construct IConstruct) *boolstatic#metric(metricName: string, props?: MetricOptions): Metricdef metric(self, metric_name: str, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metric(String metricName, MetricOptions props)public Metric Metric(string metricName, MetricOptions? props = null)func Metric(MetricName *string, Props MetricOptions) Metric#metric401ErrorRate(props?: MetricOptions): Metricdef metric401_error_rate(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metric401ErrorRate(MetricOptions props)public Metric Metric401ErrorRate(MetricOptions? props = null)func Metric401ErrorRate(Props MetricOptions) Metric#To obtain this metric, you need to set publishAdditionalMetrics to true.
metric403ErrorRate(props?: MetricOptions): Metricdef metric403_error_rate(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metric403ErrorRate(MetricOptions props)public Metric Metric403ErrorRate(MetricOptions? props = null)func Metric403ErrorRate(Props MetricOptions) Metric#To obtain this metric, you need to set publishAdditionalMetrics to true.
metric404ErrorRate(props?: MetricOptions): Metricdef metric404_error_rate(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metric404ErrorRate(MetricOptions props)public Metric Metric404ErrorRate(MetricOptions? props = null)func Metric404ErrorRate(Props MetricOptions) Metric#To obtain this metric, you need to set publishAdditionalMetrics to true.
metric4xxErrorRate(props?: MetricOptions): Metricdef metric4xx_error_rate(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metric4xxErrorRate(MetricOptions props)public Metric Metric4xxErrorRate(MetricOptions? props = null)func Metric4xxErrorRate(Props MetricOptions) Metric#metric502ErrorRate(props?: MetricOptions): Metricdef metric502_error_rate(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metric502ErrorRate(MetricOptions props)public Metric Metric502ErrorRate(MetricOptions? props = null)func Metric502ErrorRate(Props MetricOptions) Metric#To obtain this metric, you need to set publishAdditionalMetrics to true.
metric503ErrorRate(props?: MetricOptions): Metricdef metric503_error_rate(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metric503ErrorRate(MetricOptions props)public Metric Metric503ErrorRate(MetricOptions? props = null)func Metric503ErrorRate(Props MetricOptions) Metric#To obtain this metric, you need to set publishAdditionalMetrics to true.
metric504ErrorRate(props?: MetricOptions): Metricdef metric504_error_rate(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metric504ErrorRate(MetricOptions props)public Metric Metric504ErrorRate(MetricOptions? props = null)func Metric504ErrorRate(Props MetricOptions) Metric#To obtain this metric, you need to set publishAdditionalMetrics to true.
metric5xxErrorRate(props?: MetricOptions): Metricdef metric5xx_error_rate(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metric5xxErrorRate(MetricOptions props)public Metric Metric5xxErrorRate(MetricOptions? props = null)func Metric5xxErrorRate(Props MetricOptions) Metric#metricBytesDownloaded(props?: MetricOptions): Metricdef metric_bytes_downloaded(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metricBytesDownloaded(MetricOptions props)public Metric MetricBytesDownloaded(MetricOptions? props = null)func MetricBytesDownloaded(Props MetricOptions) Metric#metricBytesUploaded(props?: MetricOptions): Metricdef metric_bytes_uploaded(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metricBytesUploaded(MetricOptions props)public Metric MetricBytesUploaded(MetricOptions? props = null)func MetricBytesUploaded(Props MetricOptions) Metric#metricCacheHitRate(props?: MetricOptions): Metricdef metric_cache_hit_rate(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metricCacheHitRate(MetricOptions props)public Metric MetricCacheHitRate(MetricOptions? props = null)func MetricCacheHitRate(Props MetricOptions) Metric#HTTP POST and PUT requests, and errors, are not considered cacheable requests.
To obtain this metric, you need to set publishAdditionalMetrics to true.
metricOriginLatency(props?: MetricOptions): Metricdef metric_origin_latency(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metricOriginLatency(MetricOptions props)public Metric MetricOriginLatency(MetricOptions? props = null)func MetricOriginLatency(Props MetricOptions) Metric#This is also known as first byte latency, or time-to-first-byte.
To obtain this metric, you need to set publishAdditionalMetrics to true.
metricRequests(props?: MetricOptions): Metricdef metric_requests(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metricRequests(MetricOptions props)public Metric MetricRequests(MetricOptions? props = null)func MetricRequests(Props MetricOptions) Metric#metricTotalErrorRate(props?: MetricOptions): Metricdef metric_total_error_rate(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metricTotalErrorRate(MetricOptions props)public Metric MetricTotalErrorRate(MetricOptions? props = null)func MetricTotalErrorRate(Props MetricOptions) Metric#toString(): stringdef to_string(self, ) -> strpublic String toString()public string ToString()func ToString() *string#with(...mixins: IMixin[]): IConstructdef with(self, mixins: IMixin) -> IConstructpublic IConstruct with(IMixin mixins)public IConstruct With(IMixin mixins)func With(Mixins IMixin) IConstruct#Mixins are applied in order. The list of constructs is captured at the start of the call, so constructs added by a mixin will not be visited. Use multiple with() calls if subsequent mixins should apply to added constructs.