簡體   English   中英

如何使用AWS CDK使用ApiGateway和S3設置CloudFront?

[英]How to setup CloudFront with ApiGateway and S3 using AWS CDK?

我正在嘗試使用AWS CDK設置具有2種不同來源的CloudFront發行版:

  • S3
  • ApiGateway

這是堆棧圖。

我遇到的問題是我無法正確地將API網關的域傳遞給CloudFront發行版。 這是我的嘗試:

const api = new ag.RestApi(this, "RestApi", {
    deploy: true
});

api.root
    .addResource("api")
    .addResource("photo")
    .addResource("{id}")
    .addMethod("GET", new ag.LambdaIntegration(lambdaFunction));

const url = URL.parse(api.url);
const domainName = url.hostname as string;

const dist = new cf.CloudFrontWebDistribution(this, "Distribution", {
    originConfigs: [
        {
            s3OriginSource: { s3BucketSource: bucket },
            behaviors: [{ isDefaultBehavior: true }]
        },
        {
            customOriginSource: { domainName },
            behaviors: [
                {
                    pathPattern: "/api/*"
                }
            ]
        }
    ]
});

new cdk.CfnOutput(this, "ApiUrl", { value: api.url });

如果我注釋掉originConfigs數組中的第二個對象,一切都會通過,並且ApiUrl輸出將輸出正確的值。 但是,如果我保留上面示例中的代碼,則會收到以下錯誤:

1/2 | 12:18:13 AM | UPDATE_FAILED | AWS::CloudFront::Distribution | Distribution/CFDistribution (DistributionCFDistribution882A7313) The parameter origin name cannot be null or empty. (Service: AmazonCloudFront; Status Code: 400; Error Code: InvalidArgument; Request ID: 1606f9b3-b3e1-11e9-81fd-bb6eb7bd9c83)

我正在同一架構上工作。 api.url已標記化,因此無法進行URL解析。

您需要從其他幾個屬性中構建域名。 還要設置originPath和allowedMethods。

這個originConfig為我工作:

{
  customOriginSource: {
    domainName: `${api.restApiId}.execute-api.${this.region}.${this.urlSuffix}`
  },
  originPath: `/${api.deploymentStage.stageName}`,
  behaviors: [{
    pathPattern: '/api/*',
    allowedMethods: cloudfront.CloudFrontAllowedMethods.ALL
  }]
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM