CachePolicy L2 construct
A Cache Policy configuration.
Example
// Create the simple Origin
const myBucket = new s3.Bucket(this, 'myBucket');
const s3Origin = origins.S3BucketOrigin.withOriginAccessControl(myBucket, {
originAccessLevels: [cloudfront.AccessLevel.READ, cloudfront.AccessLevel.LIST],
});
// Create the Distribution construct
const myMultiTenantDistribution = new cloudfront.Distribution(this, 'distribution', {
defaultBehavior: {
origin: s3Origin,
},
defaultRootObject: 'index.html', // recommended to specify
});
// Access the underlying L1 CfnDistribution to configure SaaS Manager properties which are not yet available in the L2 Distribution construct
const cfnDistribution = myMultiTenantDistribution.node.defaultChild as cloudfront.CfnDistribution;
const defaultCacheBehavior: cloudfront.CfnDistribution.DefaultCacheBehaviorProperty = {
targetOriginId: myBucket.bucketArn,
viewerProtocolPolicy: 'allow-all',
compress: false,
allowedMethods: ['GET', 'HEAD'],
cachePolicyId: cloudfront.CachePolicy.CACHING_OPTIMIZED.cachePolicyId
};
// Create the updated distributionConfig
const distributionConfig: cloudfront.CfnDistribution.DistributionConfigProperty = {
defaultCacheBehavior: defaultCacheBehavior,
enabled: true,
// the properties below are optional
connectionMode: 'tenant-only',
origins: [
{
id: myBucket.bucketArn,
domainName: myBucket.bucketDomainName,
s3OriginConfig: {},
originPath: "/{{tenantName}}"
},
],
tenantConfig: {
parameterDefinitions: [
{
definition: {
stringSchema: {
required: false,
// the properties below are optional
comment: 'tenantName',
defaultValue: 'root',
},
},
name: 'tenantName',
},
],
},
};
// Override the distribution configuration to enable multi-tenancy.
cfnDistribution.distributionConfig = distributionConfig;
// Create a distribution tenant using an existing ACM certificate
const cfnDistributionTenant = new cloudfront.CfnDistributionTenant(this, 'distribution-tenant', {
distributionId: myMultiTenantDistribution.distributionId,
domains: ['my-tenant.my.domain.com'],
name: 'my-tenant',
enabled: true,
parameters: [ // Override the default 'tenantName' parameter (root) defined in the multi-tenant distribution.
{
name: 'tenantName',
value: 'app',
},
],
customizations: {
certificate: {
arn: 'REPLACE_WITH_ARN', // Certificate must be in us-east-1 region and cover 'my-tenant.my.domain.com'
},
},
});
# Create the simple Origin
my_bucket = s3.Bucket(self, "myBucket")
s3_origin = origins.S3BucketOrigin.with_origin_access_control(my_bucket,
origin_access_levels=[cloudfront.AccessLevel.READ, cloudfront.AccessLevel.LIST]
)
# Create the Distribution construct
my_multi_tenant_distribution = cloudfront.Distribution(self, "distribution",
default_behavior=cloudfront.BehaviorOptions(
origin=s3_origin
),
default_root_object="index.html"
)
# Access the underlying L1 CfnDistribution to configure SaaS Manager properties which are not yet available in the L2 Distribution construct
cfn_distribution = my_multi_tenant_distribution.node.default_child
default_cache_behavior = cloudfront.CfnDistribution.DefaultCacheBehaviorProperty(
target_origin_id=my_bucket.bucket_arn,
viewer_protocol_policy="allow-all",
compress=False,
allowed_methods=["GET", "HEAD"],
cache_policy_id=cloudfront.CachePolicy.CACHING_OPTIMIZED.cache_policy_id
)
# Create the updated distributionConfig
distribution_config = cloudfront.CfnDistribution.DistributionConfigProperty(
default_cache_behavior=default_cache_behavior,
enabled=True,
# the properties below are optional
connection_mode="tenant-only",
origins=[cloudfront.CfnDistribution.OriginProperty(
id=my_bucket.bucket_arn,
domain_name=my_bucket.bucket_domain_name,
s3_origin_config=cloudfront.CfnDistribution.S3OriginConfigProperty(),
origin_path="/{{tenantName}}"
)
],
tenant_config=cloudfront.CfnDistribution.TenantConfigProperty(
parameter_definitions=[cloudfront.CfnDistribution.ParameterDefinitionProperty(
definition=cloudfront.CfnDistribution.DefinitionProperty(
string_schema=cloudfront.CfnDistribution.StringSchemaProperty(
required=False,
# the properties below are optional
comment="tenantName",
default_value="root"
)
),
name="tenantName"
)
]
)
)
# Override the distribution configuration to enable multi-tenancy.
cfn_distribution.distribution_config = distribution_config
# Create a distribution tenant using an existing ACM certificate
cfn_distribution_tenant = cloudfront.CfnDistributionTenant(self, "distribution-tenant",
distribution_id=my_multi_tenant_distribution.distribution_id,
domains=["my-tenant.my.domain.com"],
name="my-tenant",
enabled=True,
parameters=[cloudfront.CfnDistributionTenant.ParameterProperty(
name="tenantName",
value="app"
)],
customizations=cloudfront.CfnDistributionTenant.CustomizationsProperty(
certificate=cloudfront.CfnDistributionTenant.CertificateProperty(
arn="REPLACE_WITH_ARN"
)
)
)
// Create the simple Origin
Bucket myBucket = new Bucket(this, "myBucket");
IOrigin s3Origin = S3BucketOrigin.withOriginAccessControl(myBucket, S3BucketOriginWithOACProps.builder()
.originAccessLevels(List.of(AccessLevel.READ, AccessLevel.LIST))
.build());
// Create the Distribution construct
Distribution myMultiTenantDistribution = Distribution.Builder.create(this, "distribution")
.defaultBehavior(BehaviorOptions.builder()
.origin(s3Origin)
.build())
.defaultRootObject("index.html")
.build();
// Access the underlying L1 CfnDistribution to configure SaaS Manager properties which are not yet available in the L2 Distribution construct
CfnDistribution cfnDistribution = (CfnDistribution)myMultiTenantDistribution.getNode().getDefaultChild();
DefaultCacheBehaviorProperty defaultCacheBehavior = DefaultCacheBehaviorProperty.builder()
.targetOriginId(myBucket.getBucketArn())
.viewerProtocolPolicy("allow-all")
.compress(false)
.allowedMethods(List.of("GET", "HEAD"))
.cachePolicyId(CachePolicy.CACHING_OPTIMIZED.getCachePolicyId())
.build();
// Create the updated distributionConfig
DistributionConfigProperty distributionConfig = DistributionConfigProperty.builder()
.defaultCacheBehavior(defaultCacheBehavior)
.enabled(true)
// the properties below are optional
.connectionMode("tenant-only")
.origins(List.of(OriginProperty.builder()
.id(myBucket.getBucketArn())
.domainName(myBucket.getBucketDomainName())
.s3OriginConfig(S3OriginConfigProperty.builder().build())
.originPath("/{{tenantName}}")
.build()))
.tenantConfig(TenantConfigProperty.builder()
.parameterDefinitions(List.of(ParameterDefinitionProperty.builder()
.definition(DefinitionProperty.builder()
.stringSchema(StringSchemaProperty.builder()
.required(false)
// the properties below are optional
.comment("tenantName")
.defaultValue("root")
.build())
.build())
.name("tenantName")
.build()))
.build())
.build();
// Override the distribution configuration to enable multi-tenancy.
cfnDistribution.getDistributionConfig() = distributionConfig;
// Create a distribution tenant using an existing ACM certificate
CfnDistributionTenant cfnDistributionTenant = CfnDistributionTenant.Builder.create(this, "distribution-tenant")
.distributionId(myMultiTenantDistribution.getDistributionId())
.domains(List.of("my-tenant.my.domain.com"))
.name("my-tenant")
.enabled(true)
.parameters(List.of(ParameterProperty.builder()
.name("tenantName")
.value("app")
.build()))
.customizations(CustomizationsProperty.builder()
.certificate(CertificateProperty.builder()
.arn("REPLACE_WITH_ARN")
.build())
.build())
.build();
// Install: dotnet add package Amazon.CDK.Lib
// Create the simple Origin
var myBucket = new Bucket(this, "myBucket");
var s3Origin = S3BucketOrigin.WithOriginAccessControl(myBucket, new S3BucketOriginWithOACProps {
OriginAccessLevels = new [] { AccessLevel.READ, AccessLevel.LIST }
});
// Create the Distribution construct
var myMultiTenantDistribution = new Distribution(this, "distribution", new DistributionProps {
DefaultBehavior = new BehaviorOptions {
Origin = s3Origin
},
DefaultRootObject = "index.html"
});
// Access the underlying L1 CfnDistribution to configure SaaS Manager properties which are not yet available in the L2 Distribution construct
var cfnDistribution = (CfnDistribution)myMultiTenantDistribution.Node.DefaultChild;
var defaultCacheBehavior = new DefaultCacheBehaviorProperty {
TargetOriginId = myBucket.BucketArn,
ViewerProtocolPolicy = "allow-all",
Compress = false,
AllowedMethods = new [] { "GET", "HEAD" },
CachePolicyId = CachePolicy.CACHING_OPTIMIZED.CachePolicyId
};
// Create the updated distributionConfig
var distributionConfig = new DistributionConfigProperty {
DefaultCacheBehavior = defaultCacheBehavior,
Enabled = true,
// the properties below are optional
ConnectionMode = "tenant-only",
Origins = new [] { new OriginProperty {
Id = myBucket.BucketArn,
DomainName = myBucket.BucketDomainName,
S3OriginConfig = new S3OriginConfigProperty { },
OriginPath = "/{{tenantName}}"
} },
TenantConfig = new TenantConfigProperty {
ParameterDefinitions = new [] { new ParameterDefinitionProperty {
Definition = new DefinitionProperty {
StringSchema = new StringSchemaProperty {
Required = false,
// the properties below are optional
Comment = "tenantName",
DefaultValue = "root"
}
},
Name = "tenantName"
} }
}
};
// Override the distribution configuration to enable multi-tenancy.
cfnDistribution.DistributionConfig = distributionConfig;
// Create a distribution tenant using an existing ACM certificate
var cfnDistributionTenant = new CfnDistributionTenant(this, "distribution-tenant", new CfnDistributionTenantProps {
DistributionId = myMultiTenantDistribution.DistributionId,
Domains = new [] { "my-tenant.my.domain.com" },
Name = "my-tenant",
Enabled = true,
Parameters = new [] { new ParameterProperty {
Name = "tenantName",
Value = "app"
} },
Customizations = new CustomizationsProperty {
Certificate = new CertificateProperty {
Arn = "REPLACE_WITH_ARN"
}
}
});
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
// Create the simple Origin
myBucket := s3.NewBucket(this, jsii.String("myBucket"))
s3Origin := origins.S3BucketOrigin_WithOriginAccessControl(myBucket, &S3BucketOriginWithOACProps{
OriginAccessLevels: []AccessLevel{
cloudfront.AccessLevel_READ,
cloudfront.AccessLevel_LIST,
},
})
// Create the Distribution construct
myMultiTenantDistribution := cloudfront.NewDistribution(this, jsii.String("distribution"), &DistributionProps{
DefaultBehavior: &BehaviorOptions{
Origin: s3Origin,
},
DefaultRootObject: jsii.String("index.html"),
})
// Access the underlying L1 CfnDistribution to configure SaaS Manager properties which are not yet available in the L2 Distribution construct
cfnDistribution := myMultiTenantDistribution.Node.defaultChild.(CfnDistribution)
defaultCacheBehavior := &DefaultCacheBehaviorProperty{
TargetOriginId: myBucket.bucketArn,
ViewerProtocolPolicy: jsii.String("allow-all"),
Compress: jsii.Boolean(false),
AllowedMethods: []*string{
jsii.String("GET"),
jsii.String("HEAD"),
},
CachePolicyId: cloudfront.CachePolicy_CACHING_OPTIMIZED().CachePolicyId,
}
// Create the updated distributionConfig
distributionConfig := &DistributionConfigProperty{
DefaultCacheBehavior: defaultCacheBehavior,
Enabled: jsii.Boolean(true),
// the properties below are optional
ConnectionMode: jsii.String("tenant-only"),
Origins: []interface{}{
&OriginProperty{
Id: myBucket.bucketArn,
DomainName: myBucket.BucketDomainName,
S3OriginConfig: &S3OriginConfigProperty{
},
OriginPath: jsii.String("/{{tenantName}}"),
},
},
TenantConfig: &TenantConfigProperty{
ParameterDefinitions: []interface{}{
&ParameterDefinitionProperty{
Definition: &DefinitionProperty{
StringSchema: &StringSchemaProperty{
Required: jsii.Boolean(false),
// the properties below are optional
Comment: jsii.String("tenantName"),
DefaultValue: jsii.String("root"),
},
},
Name: jsii.String("tenantName"),
},
},
},
}
// Override the distribution configuration to enable multi-tenancy.
cfnDistribution.distributionConfig = distributionConfig
// Create a distribution tenant using an existing ACM certificate
cfnDistributionTenant := cloudfront.NewCfnDistributionTenant(this, jsii.String("distribution-tenant"), &CfnDistributionTenantProps{
DistributionId: myMultiTenantDistribution.DistributionId,
Domains: []*string{
jsii.String("my-tenant.my.domain.com"),
},
Name: jsii.String("my-tenant"),
Enabled: jsii.Boolean(true),
Parameters: []interface{}{
&ParameterProperty{
Name: jsii.String("tenantName"),
Value: jsii.String("app"),
},
},
Customizations: &CustomizationsProperty{
Certificate: &CertificateProperty{
Arn: jsii.String("REPLACE_WITH_ARN"),
},
},
})
Initializer
new CachePolicy(scope: Construct, id: string, props?: CachePolicyProps)
CachePolicy(scope: Construct, id: str, props: typing.Optional[CachePolicyProps] = None)
new CachePolicy(Construct scope, String id, CachePolicyProps props)
new CachePolicy(Construct scope, string id, CachePolicyProps? props = null)
NewCachePolicy(Scope Construct, Id *string, Props CachePolicyProps)
Construct Props
cachePolicyNameoptionalstringcache_policy_nameoptionalstrcachePolicyNameoptionalStringCachePolicyNameoptionalstringCachePolicyNameoptional*string#Default: generated from the id
The name must only include '-', '_', or alphanumeric characters.
commentoptionalstringcommentoptionalstrcommentoptionalStringCommentoptionalstringCommentoptional*string#Default: no comment
The comment cannot be longer than 128 characters.
cookieBehavioroptionalCacheCookieBehaviorcookie_behavioroptionalCacheCookieBehaviorcookieBehavioroptionalCacheCookieBehaviorCookieBehavioroptionalCacheCookieBehaviorCookieBehavioroptionalCacheCookieBehavior= CacheCookieBehavior.none()#defaultTtloptionalDurationdefault_ttloptionalDurationdefaultTtloptionalDurationDefaultTtloptionalDurationDefaultTtloptionalDuration#Default: The greater of 1 day and minTtl
Only used when the origin does not send Cache-Control or Expires headers with the object.
enableAcceptEncodingBrotlioptionalbooleanenable_accept_encoding_brotlioptionalboolenableAcceptEncodingBrotlioptionalBooleanEnableAcceptEncodingBrotlioptionalboolEnableAcceptEncodingBrotlioptional*bool= false#enableAcceptEncodingGzipoptionalbooleanenable_accept_encoding_gzipoptionalboolenableAcceptEncodingGzipoptionalBooleanEnableAcceptEncodingGzipoptionalboolEnableAcceptEncodingGzipoptional*bool= false#headerBehavioroptionalCacheHeaderBehaviorheader_behavioroptionalCacheHeaderBehaviorheaderBehavioroptionalCacheHeaderBehaviorHeaderBehavioroptionalCacheHeaderBehaviorHeaderBehavioroptionalCacheHeaderBehavior= CacheHeaderBehavior.none()#maxTtloptionalDurationmax_ttloptionalDurationmaxTtloptionalDurationMaxTtloptionalDurationMaxTtloptionalDuration#Default: The greater of 1 year and defaultTtl
CloudFront uses this value only when the origin sends Cache-Control or Expires headers with the object.
minTtloptionalDurationmin_ttloptionalDurationminTtloptionalDurationMinTtloptionalDurationMinTtloptionalDuration= Duration.seconds(0)#queryStringBehavioroptionalCacheQueryStringBehaviorquery_string_behavioroptionalCacheQueryStringBehaviorqueryStringBehavioroptionalCacheQueryStringBehaviorQueryStringBehavioroptionalCacheQueryStringBehaviorQueryStringBehavioroptionalCacheQueryStringBehavior= CacheQueryStringBehavior.none()#Properties
AMPLIFYICachePolicyamplifyICachePolicyAMPLIFYICachePolicyAMPLIFYICachePolicyAMPLIFYICachePolicyrequiredstatic#cachePolicyIdstringcache_policy_idstrcachePolicyIdStringCachePolicyIdstringCachePolicyId*stringrequired#cachePolicyRefCachePolicyReferencecache_policy_refCachePolicyReferencecachePolicyRefCachePolicyReferenceCachePolicyRefCachePolicyReferenceCachePolicyRefCachePolicyReferencerequired#CACHING_DISABLEDICachePolicycaching_disabledICachePolicyCACHING_DISABLEDICachePolicyCACHING_DISABLEDICachePolicyCACHING_DISABLEDICachePolicyrequiredstatic#This policy is useful for dynamic content and for requests that are not cacheable.
CACHING_OPTIMIZEDICachePolicycaching_optimizedICachePolicyCACHING_OPTIMIZEDICachePolicyCACHING_OPTIMIZEDICachePolicyCACHING_OPTIMIZEDICachePolicyrequiredstatic#Query strings and cookies are not included in the cache key, and only the normalized 'Accept-Encoding' header is included.
CACHING_OPTIMIZED_FOR_UNCOMPRESSED_OBJECTSICachePolicycaching_optimized_for_uncompressed_objectsICachePolicyCACHING_OPTIMIZED_FOR_UNCOMPRESSED_OBJECTSICachePolicyCACHING_OPTIMIZED_FOR_UNCOMPRESSED_OBJECTSICachePolicyCACHING_OPTIMIZED_FOR_UNCOMPRESSED_OBJECTSICachePolicyrequiredstatic#Query strings and cookies are not included in the cache key, and only the normalized 'Accept-Encoding' header is included. Disables cache compression.
ELEMENTAL_MEDIA_PACKAGEICachePolicyelemental_media_packageICachePolicyELEMENTAL_MEDIA_PACKAGEICachePolicyELEMENTAL_MEDIA_PACKAGEICachePolicyELEMENTAL_MEDIA_PACKAGEICachePolicyrequiredstatic#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.
PROPERTY_INJECTION_IDstringproperty_injection_idstrPROPERTY_INJECTION_IDStringPROPERTY_INJECTION_IDstringPROPERTY_INJECTION_ID*stringrequiredstatic#USE_ORIGIN_CACHE_CONTROL_HEADERSICachePolicyuse_origin_cache_control_headersICachePolicyUSE_ORIGIN_CACHE_CONTROL_HEADERSICachePolicyUSE_ORIGIN_CACHE_CONTROL_HEADERSICachePolicyUSE_ORIGIN_CACHE_CONTROL_HEADERSICachePolicyrequiredstatic#USE_ORIGIN_CACHE_CONTROL_HEADERS_QUERY_STRINGSICachePolicyuse_origin_cache_control_headers_query_stringsICachePolicyUSE_ORIGIN_CACHE_CONTROL_HEADERS_QUERY_STRINGSICachePolicyUSE_ORIGIN_CACHE_CONTROL_HEADERS_QUERY_STRINGSICachePolicyUSE_ORIGIN_CACHE_CONTROL_HEADERS_QUERY_STRINGSICachePolicyrequiredstatic#Methods
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).
fromCachePolicyId(scope: Construct, id: string, cachePolicyId: string): ICachePolicy@staticmethod def from_cache_policy_id(scope: Construct, id: str, cache_policy_id: str) -> ICachePolicypublic static ICachePolicy fromCachePolicyId(Construct scope, String id, String cachePolicyId)public static ICachePolicy FromCachePolicyId(Construct scope, string id, string cachePolicyId)func FromCachePolicyId(Scope Construct, Id *string, CachePolicyId *string) ICachePolicystatic#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#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.