9

I'm trying to use the AWS CDK to setup a CloudFront distribution with 2 different origins:

  • S3
  • ApiGateway

Here's a diagram of the stack.

The problem I am having is that I can't pass the domain of the API Gateway to the CloudFront distribution properly. Here's my attempt:

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 });

If I comment out the second object in the originConfigs array, everything goes through, and the ApiUrl output prints the correct value. However, if I leave the code as in the above example, I get the following error:

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)

1 Answers1

16

I am working on the same architecture. The api.url is tokenized so url parsing will not work.

You need to build the domain name from several other properties. Also set the originPath and allowedMethods.

This originConfig worked for me:

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

Gary
  • 161
  • 1
  • 4