DEV Community

Nipun Parekh for AWS Community Builders

Posted on


CDN Invalidation using AWS Lambda Function

Alt Text

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

Creating a Lambda Function:

Alt Text

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.

Alt Text

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”,
‘Paths’: {
‘Quantity’: 1,
‘Items’: [path]
‘CallerReference’: str(time.time())

You will get your CDN ID from Cloudfront Dashboard like this


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


We have completed step 1.


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

Create HTTP API.


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 API Endpoint and execute this URL in the browser and here your CDN invalidation is created.

You can check it like this:


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


Top comments (1)

vumdao profile image
🚀 Vu Dao 🚀

We can invoke Lambda function through awscli instead of API Gateway for trigger create invalidation

Full solution of ci/cd

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.