I’m seaching a way to customize the Origin Name (TargetOriginId) of CloudFront Distributions in AWS CDK. This is my existing code:
const backendCloudfront = new cloudfront.CloudFrontWebDistribution(this, 'BackendCF', {
originConfigs: [
{
s3OriginSource: {
s3BucketSource: s3Bucket,
originAccessIdentity: oai,
},
behaviors: [{isDefaultBehavior: true}, { pathPattern: '/*', allowedMethods: cloudfront.CloudFrontAllowedMethods.GET_HEAD }],
},
],
});
This is the generated ExampleStack.template.json:
"BackendCFCFDistribution7FE8ADFE": {
"Type": "AWS::CloudFront::Distribution",
"Properties": {
"DistributionConfig": {
"CacheBehaviors": [
{
"AllowedMethods": [
"GET",
"HEAD"
],
"CachedMethods": [
"GET",
"HEAD"
],
"Compress": true,
"ForwardedValues": {
"Cookies": {
"Forward": "none"
},
"QueryString": false
},
"PathPattern": "/*",
"TargetOriginId": "origin1",
"ViewerProtocolPolicy": "redirect-to-https"
}
],
[...]
I’m talking about this line of code of the generated json:
"TargetOriginId": "origin1"
,
How to change the Origin Name of this permanently, without touching the auto-generated json?
2
Answers
I haven’t found any indication in the
CDK
documentation to support changing theTargetOriginId
, but the great thing aboutCDK
is there are L1 constructs to support cases such as these. There is still a way to achieve what you want, it is just not as pretty as the L2 constructCloudFrontWebDistribution
. Mind you under the hood L2 constructs are all made up of L1 constructs. This seems like a good open source contribution use case ๐Then once you run
cdk synth
the generated CloudFront Distribution will have the properTargetOriginId
name (I’ll provide the image of thetemplate.json
which the code snippet generated)You can use the
S3Origin
orHttpOrigin
constructor inaws-cdk-lib/aws-cloudfront-origins
to set up theoriginId
(unique origin name) – and then add it in your CF distribution config as an origin of 1/more behaviors:or