iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🔧

Implementing Maintenance Mode with CloudFront Functions and KeyValueStore using AWS CDK

に公開

Overview

Delivering SPAs like React with S3 and CloudFront is very cost-effective (almost zero cost), making it valuable during PoC or prototype development phases.
However, because these applications are updated frequently by nature, you often want to display a "Under Maintenance..." message.

In this article, I will introduce how to implement maintenance mode using CloudFront Functions.
I will proceed on the premise that all resources are created using AWS CDK, but the process should be straightforward even if you create them manually via the Management Console.

How maintenance mode is implemented with CloudFront Functions

CloudFront Functions allow you to control the content of requests and responses passing through CloudFront by setting up JavaScript functions.
Lambda@Edge is a similar service, but CloudFront Functions has stricter limitations on execution time and other factors, which in turn allows for high-speed processing.
https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-functions.html

KeyValueStore was released last year as a data store that can be used with CloudFront Functions.
https://aws.amazon.com/about-aws/whats-new/2023/11/amazon-cloudfront-keyvaluestore-globally-managed-key-value-datastore/

As the name suggests, it is a simple KVS that can be operated in various ways depending on the use case.
In this article, I use it as a storage location for a flag indicating whether maintenance mode is active, but it could also be used for other purposes, such as parameters for A/B testing or redirection settings.

Preparation

If you are using AWS CDK, it is available from at least v2.118.0.
https://github.com/aws/aws-cdk/releases/tag/v2.118.0

If your version is lower, please upgrade it. If you are already on v2.118.0 or higher, this is not necessary.

yarn upgrade aws-cdk@latest aws-cdk-lib@latest

Implementation

Let's look at the related code in order.

CloudFront Functions

First is the CloudFront Functions body itself.
As mentioned earlier, it is a simple JavaScript function.
As for the KeyValueStore ID, since it will be injected from the CDK later, it is hard-coded with the value "KVS_ID" at this stage. This string will be replaced with the correct value later.

If the maintenance mode flag obtained from the KeyValueStore is "true", only requests from permitted source IP addresses are allowed through, and a 503 response is returned for all others.

There are two points where CloudFront Functions can be inserted: ViewerRequest and ViewerResponse. Roughly speaking, these are when the request is received and when the response is returned.
In this case, although it feels a bit redundant, we use both.
We redirect the request destination to /maintenance.html in ViewerRequest and replace it with a 503 error in ViewerResponse.

assets/viewerRequest.js
import cf from 'cloudfront';
const kvsId = 'KVS_ID';
const kvsHandle = cf.kvs(kvsId);
const ALLOW_IPS = ['xxx.xxx.xxx.xxx'];

async function handler(event) {
  const request = event.request;
  const currentUri = request.uri;
  const doReplace = request.method === 'GET' && currentUri.indexOf('.') === -1;
  const clientIp = event.viewer.ip;
  const isMaintenance = await kvsHandle.get('isMaintenance');
  if (
    convertStrToBool(isMaintenance) &&
    !ALLOW_IP_LIST.includes(clientIp) &&
    doReplace
  ) {
    request.uri = '/maintenance.html';
  }
  return request;
}

function convertStrToBool(str) {
  if (typeof str != 'string') {
    return Boolean(str);
  }
  try {
    var obj = JSON.parse(str.toLowerCase());
    return obj == true;
  } catch (e) {
    return str != '';
  }
}
assets/viewerResponse.js
import cf from 'cloudfront';
const kvsId = 'KVS_ID';
const kvsHandle = cf.kvs(kvsId);
const ALLOW_IPS = ['xxx.xxx.xxx.xxx'];

async function handler(event) {
  const response = event.response;
  const request = event.request;
  const currentUri = request.uri;
  const doReplace = request.method === 'GET' && currentUri.indexOf('.') === -1;
  const clientIp = event.viewer.ip;
  const isMaintenance = await kvsHandle.get('isMaintenance');
  if (
    convertStrToBool(isMaintenance) &&
    !ALLOW_IP_LIST.includes(clientIp) &&
    doReplace
  ) {
    response.statusCode = 503;
    response.statusDescription = 'Is Maintenance.';
  }
  return response;
}

function convertStrToBool(str) {
  if (typeof str != 'string') {
    return Boolean(str);
  }
  try {
    var obj = JSON.parse(str.toLowerCase());
    return obj == true;
  } catch (e) {
    return str != '';
  }
}

CDK

Next is the code to create the necessary resources using CDK.
Some parts of the CloudFront creation are omitted. The key point is that after creating the KeyValueStore, the KVS_ID value in the previous CloudFront Functions code is replaced with the actual ID.
While a smarter way to pass the KeyValueStore reference to CloudFront Functions might emerge in the future, this was the only way available as of now (March 18, 2024). Any information is welcome.

import { Stack, StackProps } from 'aws-cdk-lib';
import * as cloudfront from 'aws-cdk-lib/aws-cloudfront';

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

    // Create KeyValueStore
    const keyValueStore = new aws_cloudfront.KeyValueStore(stack, 'KVS');

    // Load CloudFront Function code
    const viewerRequestScript = readFileSync(
        'assets/requestChecker.js',
        {
          encoding: 'utf-8'
        }
    ).replace(/\n/g, '');
    const viewerResponseScript = readFileSync(
        'assets/viewerResponse.js',
        {
          encoding: 'utf-8'
        }
    ).replace(/\n/g, '');

    // Create CloudFront Functions
    const requesetFn = new cloudfront.Function(stack, 'ViewerRequest', {
        // Specify KeyValueStore
        keyValueStore,
        // Set runtime
        runtime: cloudfront.FunctionRuntime.JS_2_0,
        // Replace the string "KVS_ID" in the loaded code with the actual KeyValueStore ID
        code: cloudfront.FunctionCode.fromInline(
            viewerRequestScript.replace('KVS_ID',keyValueStore.keyValueStoreId)
        )
    });
    const responseFn = new cloudfront.Function(stack, 'ViewerResponse', {
        keyValueStore,
        runtime: cloudfront.FunctionRuntime.JS_2_0,
        code: cloudfront.FunctionCode.fromInline(
            viewerResponseScript.replace('KVS_ID',keyValueStore.keyValueStoreId)
        )
    });

    // Create CloudFront Distribution
    const distribution = new cloudfront.Distribution(this, 'SampleDistribution', {
      defaultRootObject: 'index.html',
      defaultBehavior: {
        // ...Some parts omitted
        // Link CloudFront Functions
        functionAssociations: [
            // Link at both request and response timings
            {
                function: requestFn,
                eventType: cloudfront.FunctionEventType.VIEWER_REQUEST,
            },
            {
                function: responseFn,
                eventType: cloudfront.FunctionEventType.VIEWER_RESPONSE,
            },
        ],
      },
    });

  }
}

This completes the KeyValueStore and the CloudFront Functions that reference it.
Now, all that's left is to put the necessary values into the KeyValueStore.
*Of course, it is also possible to set these values when defining the KeyValueStore in CDK. In that case, you would specify the source during declaration.

KeyValueStore Settings

When configuring from the Management Console, you can do so via Edit, just like with other services.
1

Enter values with the isMaintenance key to ensure consistency with the CloudFront Functions logic. Note that when handled in CloudFront Functions, these values are treated as string types, such as "false".
2

Configuring via the SDK

It is also possible to set values using the SDK.
Below is a sample code for updating KeyValueStore values from Lambda.

import { Handler } from 'aws-lambda';
import {
  CloudFrontKeyValueStoreClient,
  DescribeKeyValueStoreCommand,
  PutKeyCommand
} from '@aws-sdk/client-cloudfront-keyvaluestore';
import '@aws-sdk/signature-v4-crt';

const client = new CloudFrontKeyValueStoreClient({ region: 'us-east-1' });

export const handler: Handler = async () => {
  try {
    // First, retrieve the KVS
    const kvs = await client.send(
      new DescribeKeyValueStoreCommand({
        KvsARN: 'xxxxxxxxxx'
      })
    );
    // Specify information such as the ETag and ARN of the retrieved KVS, plus the Key and Value you want to update
    const data = await client.send(
      new PutKeyCommand({
        KvsARN: kvs.KvsARN,
        Key: 'isMaintenance',
        Value: 'false',
        IfMatch: kvs.ETag
      })
    );
  } catch (err) {
    console.error(err);
  }
};
export default handler;

Closing Thoughts

In this article, I summarized how to implement maintenance mode for static sites or SPAs using CloudFront Functions and KeyValueStore.
Since this post focused on the frontend, I didn't mention it specifically, but when enabling maintenance mode, the backend also needs to be handled.
Common examples include ALB + ECS/EC2 or API Gateway.
The methods vary for each, but articles like the following might be helpful:

https://zenn.dev/yumemi_inc/articles/f1f8a8269da4a9

https://zenn.dev/rescuenow/articles/c85265894b6efd

I hope the content of this article is helpful.

References

https://dev.classmethod.jp/articles/aws-cdk-supports-cloudfront-keyvaluestore-l2-construct/

https://dev.classmethod.jp/articles/aws-cdk-v2-124-0-supports-association-of-cloudfront-keyvaluestore-with-functions/

https://qiita.com/yokku21/items/1fd3667b74577db5db12

Discussion