amazon-web-servicesamazon-cloudfrontaws-cdkcache-control

How to add cache-control header to existing responseHeaderPolicy in aws CDK Cloudfront?


I have an AWS CDK Cloudfrount distribution with the default responseHeaderPolicy. I need to add a cache-control directive, but it seems that I have to create from scratch the whole ResponseHeaderPolicy, that includes CORS policies and other configuration that I am fine with the defaults. Is there a way to edit the default responseHeaderPolicy just to add the cache-control, instead of having to build the whole object?

This is my current configuration:

const cf = new cloudfront.Distribution(this, `cdn-${this.env}`, {
  defaultBehavior: { 
      origin: new origins.S3Origin(this.cdnBucket),
      cachePolicy: custom_policy,
      allowedMethods: cloudfront.AllowedMethods.ALLOW_GET_HEAD_OPTIONS,
      originRequestPolicy: cloudfront.OriginRequestPolicy.CORS_S3_ORIGIN,
      responseHeadersPolicy: cloudfront.ResponseHeadersPolicy.CORS_ALLOW_ALL_ORIGINS_WITH_PREFLIGHT,
    },
  domainNames: [domain],
  certificate,
});

Solution

  • No, it's not possible for your CDK code to make incremental modifications to a predefined Response Header Policy like CORS_ALLOW_ALL_ORIGINS_WITH_PREFLIGHT.

    The reason is that the CDK policy corresponds to a CloudFront managed policy. The CDK only knows the policy ID (5cc3b908-e619-4b99-88e5-2cf7f45965bd), which it passes to the distribution. The content of the policy itself is not defined in the CDK.