Search code examples
amazon-web-servicesamazon-cloudfrontaws-cdk

Migrate a CDK managed CloudFormation distribution from the CloudFrontWebDistribution to the Distribution API


I have an existing CDK setup in which a CloudFormation distribution is configured using the deprecated CloudFrontWebDistribution API, now I need to configure a OriginRequestPolicy, so after some Googling, switched to the Distribution API (https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cloudfront-readme.html) and reused the same "id" - Distribution distribution = Distribution.Builder.create(this, "CFDistribution") When I synth the stack I already see in the yaml that the ID - e.g. CloudFrontCFDistribution12345689 - is a different one than the one before. When trying to deploy it will fail, since the HTTP Origin CNAMEs are already associated with the existing distribution. ("Invalid request provided: One or more of the CNAMEs you provided are already associated with a different resource. (Service: CloudFront, Status Code: 409, Request ID: 123457657, Extended Request ID: null)"

Is there a way to either add the OriginRequestPolicy (I just want to transfer an additional header) to the CloudFrontWebDistribution or a way to use the new Distribution API while maintaining the existing distribution instead of creating a new one? (The same operation takes around 3 clicks in the AWS Console).


Solution

  • You could use the following trick to assign the logical ID yourself instead of relying on the autogenerated logical ID. The other option is to execute it in two steps, first update it without the additional CNAME and then do a second update with the additional CNAME.

    const cfDistro = new Distribution(this, 'distro', {...});
    cfDistro.node.defaultChild.overrideLogicalId('CloudfrontDistribution');
    

    This will result in the following stack:

    CloudfrontDistribution:
      Type: AWS::CloudFront::Distribution
      Properties:
      ...
    

    Small edit to explain why this happens:

    Since you're switching to a new construct, you're also getting a new logical ID. In order to ensure a rollback is possible, CloudFormation will first create all new resources and create the updated resources that need to be recreated. Only when creating and updating everything is done, it will clean up by removing the old resources. This is also the reason why a two-step approach would work when changing the logical IDs of the resources, or force a normal update by ensuring the same logical ID.