Clearing The cache of cloudfront in serverless deployment using AWS Codepipeline and lambda function

Shaharyar
2 min readJul 7, 2021

Recently I did serverless deployment for one of the project in VUE.js using the S3 and cloudfront but after each release I have to manually clear the cache of the cloudfront which doesn’t fulfill the motive of the AWS Codepipeline for a automated deployment

So I need to figure out what exactly I can do to clear cache of the cloudfront but before that it is necessary to know when exactly I need to clear cache.

When exactly I need to clear cache ?

In serverless deployment cloudfront cache the build file from s3 to edge location for faster access by the client therefore whenever new build artifact are uploaded to the S3 I need to clear cache that is must be part of deploy stage.

How I can do it ?

In each stage I can add action which according to the documentation of AWS is part of the sequence in a stage of a pipeline. It is a task performed on the artifact in that stage. Pipeline actions occur in a specified order, in sequence or in parallel, as determined in the configuration of the stage.

In deployment stage I added the lambda function as the action which execute after the uploading artifact to the s3 bucket and clear the cache of the cloudfront and new build file can be delivered from origin and can cached further at the edge location.

So lambda function to execute as action will be

const AWS = require('aws-sdk');exports.handler = async (event) => {
const cloudfront = new AWS.CloudFront();
const codepipeline = new AWS.CodePipeline();
const distId = "************". // put your own distribution id
await cloudfront.createInvalidation({
DistributionId: distId,
InvalidationBatch: {
CallerReference: new Date().getTime().toString(),
Paths: {
Quantity: 1,
Items: ['/*'],
},
},
}).promise();
const params = {
"jobId"=event['CodePipeline.job']['id']
}

codepipeline.putJobSuccessResult(params, function(err, data) {
if (err) console.log(err, err.stack);
else return data
});
};

Important notes:

  1. Assign lambda a permission to invalidate the cloudfront and also put job success result to codepipeline by attaching policy to access the cloudfront and codepipeline

--

--