Reputation: 1297
I'm just learning AWS CDK after playing around with Serverless for a bit.
Serverless has a component to deploy a static website, which uses S3 and CloudFront. It updates an existing CloudFront distribution if it finds one for the same domain. Presumably the reason why it does this is so you don't have to wait 40 minutes while the CloudFront distribution is set up. I can't think of any other reason for it, e.g. it would seem to cost the same.
So how do you search for and re-use an existing CloudFront distribution in CDK? Should you actually just create a new one?
Upvotes: 4
Views: 3621
Reputation: 11
const distribution = Distribution.fromDistributionAttributes(scope, 'distribution', {
distributionId: 'foo',
domainName: 'bar.cloudfront.net'
});
Link to AWS Docs: https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront-readme.html#importing-distributions
Of note is that "an imported distribution cannot be modified"
Upvotes: 1
Reputation: 8941
AWS CDK allows to use custom resources which are executed lambda functions that run AWS SDK actions and allow consuming the results for further processing.
This would allow the following approach to search for the existing CF Distribution (in typescript
)
const cloudFrontDistributions = new customResources.AwsCustomResource(this, 'cloud-front-distribution-list', {
onCreate: {
physicalResourceId: 'cloud-front-distribution-list',
service: 'CloudFront',
action: 'listDistributions',
}
});
const distributionList = JSON.parse(cloudFrontDistributions.getData('DistributionList'));
than you can search for the distribution using typescript. Same can be done in the other cdk languages.
It should be possible to use the same find predicate as in the link you provided:
const distribution = distributionList.Items.find((dist) =>
dist.Aliases.Items.includes(domain)
)
Sadly it does look like there is no way to import the Distribution into AWS CDK at the moment, i will raise a feature request on the github repo. I will update as soon as it is possible to import a CloudFront distribution.
Upvotes: 2