【问题标题】:How to setup CloudFront with ApiGateway and S3 using AWS CDK?如何使用 AWS CDK 使用 ApiGateway 和 S3 设置 CloudFront?
【发布时间】:2019-12-09 12:01:18
【问题描述】:

我正在尝试使用 AWS CDK 设置具有 2 个不同来源的 CloudFront 分配:

  • S3
  • ApiGateway

Here's a diagram of the stack.

我遇到的问题是我无法将 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)

【问题讨论】:

    标签: typescript aws-api-gateway amazon-cloudfront aws-cdk


    【解决方案1】:

    我正在研究相同的架构。 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
      }]
    }
    
    

    【讨论】:

    猜你喜欢
    • 2022-01-01
    • 2021-09-20
    • 2020-08-13
    • 2014-10-14
    • 1970-01-01
    • 2020-06-04
    • 2016-11-13
    • 1970-01-01
    • 2019-09-15
    相关资源
    最近更新 更多