CDN Invalidation using AWS Lambda Function

Steps to create Invalidation using lambda function are:

  1. Create a Lambda Function and write a code.
  2. Create an API Gateway / API from which we are going to create Invalidation of CDN

Step:1

Creating a Lambda Function:

Lambda Function

Just give a name of the function and use the Runtime of python 3.8 and put rest all things as it is.

Now Click on Create Button and Your Function is created.

When you go inside a function you will find this window.

Inside Lambda Function

Paste this code inside the code area.

from __future__ import print_function

import boto3
import time

def lambda_handler(event, context):
client = boto3.client(‘cloudfront’)
path = “/*”
invalidation = client.create_invalidation(DistributionId=”Put your CDN ID”,
InvalidationBatch={
‘Paths’: {
‘Quantity’: 1,
‘Items’: [path]
},
‘CallerReference’: str(time.time())
})

You will get your CDN ID from Cloudfront Dashboard like this

Here is your CDN ID

Now attach the Cloudfront full access policy to our lambda policy like this.

Attach Cloudfront full access policy

We have completed step 1.

Step:2

Create an API for that you have to use AWS API Gateway Service.

Create HTTP API.

Create API this way

The Integration, section adds lambda and selects your lambda function in my case it is an invalidation name of the function.

And rest all thing keep as it is and create an API.

We have successfully completed all the steps.

Now come to the lambda function and reload our lambda function page and you will get our API Gateway in the trigger section like this.

Now Click on API Gateway you will get something page like this:

Click on the API endpoint

Click on API Endpoint and execute this URL in the browser and here your CDN invalidation is created.

You can check it like this:

It will be there in the progress stage

So here we Created a CND Invalidation using AWS Lambda Function.

Thank you for reading this blog, hope you learned some new thing.

Still, if you have any query you can refer to my video

Still, you have any doubt you can contact me on LinkedIn

LinkedIn: https://www.linkedin.com/in/nipun-parekh-6006a0152/

DevOps enthusiast.