Create a configuration to access the Endpoint of the Lambda Function URL via CloudFront using a custom domain.

Page content

Introduction

The configuration is to access the endpoint of a Lambda Function URL via CloudFront using a custom domain. There are similar configurations such as

  • Lambda + API Gateway
  • Lambda@Edge

but this time we will use this configuration.

Point

  • Obtain the Endpoint URL of the Lambda Function URL automatically and set it to CloudFront’s Origin (somewhat cumbersome).
  • The Lambda Function should be simple enough to access DynamoDB.
  • Create a new A record for the custom domain and set that A record to the CloudFront Alias.
    • Assume that the custom domain is in the Hosted Zone of Route53.
    • The SSL certificate is also issued by ACM.

Version

  • aws-cdk: 2.46.0

How to write

Write like this.

import * as cdk from "aws-cdk-lib";
import { Construct } from "constructs";

import * as lambda from "aws-cdk-lib/aws-lambda";
import * as iam from "aws-cdk-lib/aws-iam";
import * as nodejs from "aws-cdk-lib/aws-lambda-nodejs";
import * as cloudfront from "aws-cdk-lib/aws-cloudfront";
import * as route53 from "aws-cdk-lib/aws-route53";
import * as targets from "aws-cdk-lib/aws-route53-targets";
import * as acm from "aws-cdk-lib/aws-certificatemanager";

const NAME = "MyAwesomeResource";

const domainName = "mydomain.example.com";
const cloudFrontHostName = "my-awesome-resource.mydomain.example.com";

export class ExternalMasterStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    const { functionUrl, lambdaFunction } = this.createLambdaFunction();

    // get token for CloudFront Origin
    const lambdaHostName = cdk.Lazy.uncachedString({
      produce: (context) => {
        const resolved = context.resolve(functionUrl.url);
        return { "Fn::Select": [2, { "Fn::Split": ["/", resolved] }] } as any;
      },
    });

    this.createCloudFront(lambdaHostName);
  }

  // create lambda function
  createLambdaFunction(): {
    functionUrl: lambda.FunctionUrl;
    lambdaFunction: lambda.Function;
  } {
    // NodejsFunction
    const lambdaFunction = new nodejs.NodejsFunction(this, `${NAME}Lambda`, {
      functionName: `${NAME}-function`,
      entry: "src/lambda/index.ts", // lambda function source code
      handler: "handler",
      memorySize: 128,
      bundling: {
        minify: true,
        sourceMap: true,
        target: "es2020",
        externalModules: ["aws-sdk"],
      },
      runtime: lambda.Runtime.NODEJS_16_X,
    });

    // add function url
    const functionUrl = lambdaFunction.addFunctionUrl({
      authType: lambda.FunctionUrlAuthType.NONE, // no auth
      cors: {
        allowedMethods: [lambda.HttpMethod.GET], // only GET
        allowedOrigins: ["*"], // allow all origins for CORS
      },
    });

    // add tags for lambda function
    cdk.Tags.of(lambdaFunction).add("Name", `${NAME}Lambda`);
    cdk.Tags.of(lambdaFunction).add("Project", NAME);

    // allow lambda function to get dynamodb items in tables that start with "my-awesome-resource."
    lambdaFunction.addToRolePolicy(
      new iam.PolicyStatement({
        effect: iam.Effect.ALLOW,
        actions: ["dynamodb:GetItem"],
        resources: [
          `arn:aws:dynamodb:${this.region}:${this.account}:table/my-awesome-resource.*`,
        ],
      })
    );

    return { lambdaFunction, functionUrl };
  }

  createCloudFront(originHost: string) {
    // Hosted Zone
    const hostedZoneId = route53.HostedZone.fromLookup(this, "hostedZoneId", {
      domainName: domainName,
    });

    // SSL Certificate
    const certificateManagerCertificate = new acm.DnsValidatedCertificate(
      this,
      "CertificateManagerCertificate",
      {
        domainName: cloudFrontHostName,
        hostedZone: hostedZoneId,
        region: "us-east-1",
        validation: acm.CertificateValidation.fromDns(),
      }
    );

    // CloudFront
    const cloudFront = new cloudfront.CloudFrontWebDistribution(
      this,
      `${NAME}CloudFront`,
      {
        comment: `${NAME} CloudFront`,
        originConfigs: [
          {
            behaviors: [
              {
                isDefaultBehavior: true,
                allowedMethods:
                  cloudfront.CloudFrontAllowedMethods.GET_HEAD_OPTIONS, // only GET HEAD OPTIONS
                compress: true,
                forwardedValues: {
                  queryString: true, // forward query string
                  // no cookies
                  cookies: {
                    forward: "none",
                  },
                },
              },
            ],
            // Lambda Function URL
            customOriginSource: {
              domainName: originHost,
            },
          },
        ],
        // https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/PriceClass.html
        priceClass: cloudfront.PriceClass.PRICE_CLASS_200, // Price Class 200.
        viewerCertificate: cloudfront.ViewerCertificate.fromAcmCertificate(
          certificateManagerCertificate,
          {
            securityPolicy: cloudfront.SecurityPolicyProtocol.TLS_V1_2_2021,
            aliases: [cloudFrontHostName],
          }
        ),
      }
    );
    // add tags to CloudFront
    cdk.Tags.of(cloudFront).add("Name", `${NAME}CloudFront`);
    cdk.Tags.of(cloudFront).add("Project", NAME);

    // Route53
    new route53.ARecord(this, `${NAME}ARecord`, {
      recordName: cloudFrontHostName,
      zone: hostedZoneId,
      target: route53.RecordTarget.fromAlias(
        new targets.CloudFrontTarget(cloudFront)
      ),
    });
  }
}

Afterward

You may not need this kind of configuration since you have Lambda@Edge, but I think some parts of the code may be helpful. However, some parts of the code may be useful, so I leave it as a note.