typescript - 如何使用 AWS CDK 使用 ApiGateway 和 S3 设置 CloudFront?
问题描述
我正在尝试使用 AWS CDK 设置具有 2 个不同来源的 CloudFront 分配:
- S3
- ApiGateway
我遇到的问题是我无法将 API Gateway 的域正确传递给 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
}]
}