Search code examples
amazon-web-servicesssl-certificateaws-cloudformationamazon-cloudfrontaws-cdk

How to add domain alias to existing CloudFront distribution using AWS CDK


I just deployed a CloudFormation solutions from the AWS Solutions. The solutions included a new CloudFront distribution. My challenge is that I want to add a custom domain mysite.example.com to the dxxxxxx.cloudfront.net distribution. I already created an alias and certificate using Certificate Manager. My question is how do I add a new domain to the existing CloudFront.

I understand that we can import an existing distribution using Distribution.fromDistributionAttributes.

for example

const distribution = cloudfront.Distribution.fromDistributionAttributes(this, 'ImportedDist', {
  domainName: 'd111111abcdef8.cloudfront.net',
  distributionId: '012345ABCDEF',
});

Let's say I have the alias domain name and certificate ARN ready to use.

const domainName = 'mysite.example.com';
const certificateArn = 'arn:aws:acm:us-east-1: 123456789012:certificate/abcdefgh-1234-5678-9012-abcdefghujkl';

Where do I go from here?


Solution

  • Add your domain and certificate by updating your "AWS solutions" CDK app. CDK apps are designed be modified and redeployed.

    The Distribution construct accepts the certificate?:ICertificate and domainNames?: string[] as props to the constructor. Instances also expose a addBehavior(pathPattern, origin, behaviorOptions?), which seems handy.

    If the app is in production, be mindful that updates sometimes result in resource replacement or interruption. The CloudFormation docs note the update behaviour for each service property. In the happy case you will see Update requires: No interruption. Run the cdk diff command to preview the changes CloudFormation will make to your resources.

    What about cloudfront.Distribution.fromDistributionAttributes? Many CDK classes have static from... methods to get a reference to an existing AWS resource. These methods are handy (or even necessary) when resources are shared between apps, but should be used only when you cannot modify the original CDK construct.