Written by , Updated on March 16, 2021

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

import boto3

import time

# Create CloudFront client

cf = boto3.client(‘cloudfront’)

# Enter Original name

DISTRIBUTION_ID = “UJS7S8D8FD8FDF”

# Create CloudFront invalidation

def create_invalidation():

    res = cf.create_invalidation(

        DistributionId=DISTRIBUTION_ID,

        InvalidationBatch={

            ‘Paths’: {

                ‘Quantity’: 1,

                ‘Items’: [

                    ‘/*’

                ]

            },

            ‘CallerReference’: str(time.time()).replace(“.”, “”)

        }

    )

    invalidation_id = res[‘Invalidation’][‘Id’]

    return invalidation_id

# Create CloudFront Invalidation

id = create_invalidation()

print(“Invalidation created successfully with Id: “ id)

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.

Python Script to Create CloudFront Invalidations AWS Boto3 Cloudfront General Articles Python

Now, execute Python script from a terminal to create invalidation request.

python3 create_invalidation.py

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.

Python Script to Create CloudFront Invalidations AWS Boto3 Cloudfront General Articles Python

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

import boto3

import time

# Create CloudFront client

cf = boto3.client(‘cloudfront’)

# Create CloudFront invalidation

def create_invalidation(DISTRIBUTION_ID):

    res = cf.create_invalidation(

        DistributionId=DISTRIBUTION_ID,

        InvalidationBatch={

            ‘Paths’: {

                ‘Quantity’: 1,

                ‘Items’: [

                    ‘/*’

                ]

            },

            ‘CallerReference’: str(time.time()).replace(“.”, “”)

        }

    )

    invalidation_id = res[‘Invalidation’][‘Id’]

    return invalidation_id

# Loop through all distributions

distributions=cf.list_distributions()

if distributions[‘DistributionList’][‘Quantity’] > 0:

  for distribution in distributions[‘DistributionList’][‘Items’]:

    id = create_invalidation(distribution[‘Id’])

    print(“Invalidation created successfully for – “ distribution[‘Id’])

else:

  print(“No CloudFront distributions found.”)

Conclusion

This tutorial helped you with a Python script to create CloudFront invalidation request.