DEV Community

Cover image for Invalidation AWS CDN Using Boto3
🚀 Vu Dao 🚀
🚀 Vu Dao 🚀

Posted on

4 2

Invalidation AWS CDN Using Boto3

  • This post describe how to remove files from CloudFront edge caches before it expires using python boto3

  • To invalidate files, specify either the path for individual files or a path that ends with the * wildcard, which might apply to one file or to many, as shown in the following examples:

    • /images/image1.jpg
    • /images/image*
    • /images/* Alt Text
  • Using python boto3 invalidatecdn_demo.py

    
    

import boto3
import time
import sys

""" Invalidate CDN at s3://static/demo/src """
DISTRIBUTION_ID = 'A1AA1AA11A11AA'

client = boto3.client('cloudfront')

def create_invalidation():
res = client.create_invalidation(
DistributionId=DISTRIBUTION_ID,
InvalidationBatch={
'Paths': {
'Quantity': 1,
'Items': [
'/demo/src/*'
]
},
'CallerReference': str(time.time()).replace(".", "")
}
)
invalidation_id = res['Invalidation']['Id']
return invalidation_id

def get_invalidation_status(inval_id):
res = client.get_invalidation(
DistributionId=DISTRIBUTION_ID,
Id=inval_id
)
return res['Invalidation']['Status']

def run():
the_id = create_invalidation()
count = 0
while True:
status = get_invalidation_status(the_id)
if status == 'Completed':
print("Completed, id: {}".format(the_id))
break
elif count < 10:
count += 1
time.sleep(30)
else:
print("Timeout, please check CDN")
sys.exit(1)

if name == 'main':
run()


- Run
Enter fullscreen mode Exit fullscreen mode

~()⚡ $ python invalidatecdn_demo.py
Completed, id: I1CLODB5ZXEQUK


- Result
 - In progress
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/b0f6fgc459dkvc1741hh.png)

 - Complete
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/f62t39vkyjr1opqhnoxt.png)

- Ref: https://github.com/vumdao/invalidate-cdn/tree/master
Enter fullscreen mode Exit fullscreen mode

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

Try REST API Generation for Snowflake

DevOps for Private APIs. Automate the building, securing, and documenting of internal/private REST APIs with built-in enterprise security on bare-metal, VMs, or containers.

  • Auto-generated live APIs mapped from Snowflake database schema
  • Interactive Swagger API documentation
  • Scripting engine to customize your API
  • Built-in role-based access control

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay