Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maintenance mode using S3 + CloudFront

I'm serving a single page app that is hosted on S3 and exposed to the web via CloudFront. When I'm performing maintenance on my API, I'd like to have a manual switch that causes the request to my app to render a maintenance page.

I can put the maintenance HTML (or json) to the S3. How to configure CloudFront to return the maintenance site when I switch the maintenance mode on?

like image 406
Matic Jurglič Avatar asked Dec 08 '22 16:12

Matic Jurglič


1 Answers

Create a Lambda@Edge function to generate your static "maintenance" response: http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-examples.html#lambda-examples-static-web-server

When you want to activate it, select Viewer Request trigger and use the Lambda function's ARN on the settings page for the Cache Behavior(s) that you want to return the maintenance message, and save changes. To deactivate it, remove it. The change is usually processed within a very short period of time.

This will accomplish your purpose because a Viewer Request trigger fires before the CloudFront cache is checked, and if it generates a response, the response is returned without checking the cache and the generated response is not stored in the CloudFront cache -- so any cached content will still be there after you remove the trigger.

Note that the first time you actually associate a function like this with a CloudFront distribution, I believe that you need to "enable trigger and replicate" in the Lambda console so that the Lambda function is globally accessible when CloudFront needs it. You don't have to associate it with the "real" CloudFront distribution when testing this -- you can create a second one for testing -- but a function version needs to go through this replication cycle before it can be used in the CloudFront console. Functions for use with Lambda@Edge must be created in the us-east-1 region, and are then replicated to all regions so that a CloudFront edge can invoke it via its nearest region. Lambda@Edge functions are always referenced by their numeric version id. Function aliases, including the magic string $LATEST are not used by Lambda@Edge.

like image 51
Michael - sqlbot Avatar answered Dec 28 '22 13:12

Michael - sqlbot