DEV Community

loading...
AWS Community Builders

CDN Invalidation using AWS Lambda Function

Nipun Parekh
I am AWS, Oracle * 3 times cloud certified. I am AWS,Microsoft student ambassador., and Google DSC GCP Head.
・2 min read

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

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

You will get your CDN ID from Cloudfront Dashboard like this

image

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

image

We have completed step 1.

Step:2

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

Create HTTP API.

image

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

image

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

image

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

You can check it like this:

image

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

https://www.youtube.com/watch?v=sDT1sg72fUY

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

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

Discussion (1)

Collapse
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 dev.to/vumdao/ci-cd-for-cdn-invali...