Amazon CloudFront invalidation feature allows you to remove an object from the CloudFront cache before it expires. It allows you to remove a specific object from cache or use (*) wildcard character to remove multiple objects. You can also invalidate all the objects by using “/*” parameters to invalidation requests.
Python Script to Create CloudFront Invalidation
Boto3 is the AWS SDK for the Python programming language. It allows Python developers to write programs that makes use of services like CloudFront, S3 and Ec2 etc.
First, you need to install Boto3 Python library based on the Python version installed on your system. We recommened to use Python 3 to run below scripts.
pip install boto3
##For Python 2 or default
pip3 install boto3
##For Python 3
Next, create a Python script with the following content.
You must have to change DISTRIBUTION_ID value to the actual CloudFront distribution name. To find distribution name visit CloudFront web interface. There you can find Distribution id under the ID column.
Now, execute Python script from a terminal to create invalidation request.
On successful execution, you will see a message on screen like:
Invalidation created successfully with Id: I3HHNHJ0AF0ILQ
The Invalidation request may take some time based on cached data. You can see the invalidation request status on CloudFront web interface.
To view invalidation status, Go to CloudFront web interface. Open CloudFront distribution, then navigate to Invalidations tab. See the status of Invalidation request Id shown in above output.
Create Invalidation for All CloudFront Distribution’s
You can also use the following Python script to create Invalidation request for all CloudFront distributions available in selected region of your AWS account.
This tutorial helped you with a Python script to create CloudFront invalidation request.