如何在 AWS CDK 中为 CloudFront 设置自定义源名称

问题描述 投票:0回答:1

我正在寻找一种在 AWS CDK 中自定义 CloudFront Distributions 的原始名称 (TargetOriginId) 的方法。这是我现有的代码:

const backendCloudfront = new cloudfront.CloudFrontWebDistribution(this, 'BackendCF', {
  originConfigs: [
    {
      s3OriginSource: {
        s3BucketSource: s3Bucket,
        originAccessIdentity: oai,
      },
      behaviors: [{isDefaultBehavior: true}, { pathPattern: '/*', allowedMethods: cloudfront.CloudFrontAllowedMethods.GET_HEAD }],
    },
  ],
});

这是生成的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"
      }
     ],
[...]

我说的是生成的json的这行代码:

"TargetOriginId": "origin1"
,

如何永久更改其原始名称,而不触及自动生成的 json?

Screenshot of the AWS Console referring to Origin Name

amazon-web-services amazon-s3 aws-cloudformation amazon-cloudfront aws-cdk
1个回答
0
投票

我没有在

CDK
文档 中找到任何支持更改
TargetOriginId
的指示,但
CDK
的伟大之处在于有 L1 构造来支持此类情况。还有一种方法可以实现你想要的,只是不如 L2 构造
CloudFrontWebDistribution
那么漂亮。请注意,在底层,L2 结构都是由 L1 结构组成的。这似乎是一个很好的开源贡献用例;)

    const s3Bucket = new Bucket(this, "my-bucket");
    const oai = new OriginAccessIdentity(this, "my-oia");

    // Define the CloudFront distribution with CfnDistribution instead
    const backendCloudfront = new CfnDistribution(this, "BackendCF", {
      distributionConfig: {
        enabled: true,
        origins: [
          {
            domainName: s3Bucket.bucketDomainName,
            id: "myTargetName",
            s3OriginConfig: {
              originAccessIdentity: oai.originAccessIdentityId,
            },
          },
        ],
        defaultCacheBehavior: {
          targetOriginId: "myTargetName", // Referencing the origin by its ID above
          viewerProtocolPolicy: "allow-all",
          // Further configuration as needed
        },
        // Additional configuration: cache behaviors, comment, custom error responses, etc.
      },
    });

然后,一旦您运行

cdk synth
,生成的 CloudFront Distribution 将具有正确的
TargetOriginId
名称(我将提供代码片段生成的
template.json
的图像)

© www.soinside.com 2019 - 2024. All rights reserved.