Facebook Twitter Instagram
    TecAdmin
    • Home
    • FeedBack
    • Submit Article
    • About Us
    Facebook Twitter Instagram
    TecAdmin
    You are at:Home»General Articles»Python Script to Create CloudFront Invalidations

    Python Script to Create CloudFront Invalidations

    By RahulMarch 16, 20212 Mins Read

    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.

    Advertisement

    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.

    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.

    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.

    aws Boto3 Cloudfront Python
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email WhatsApp

    Related Posts

    20 Basic Linux Commands for the Beginners (Recommended)

    tail Command in Linux with Examples

    What is a Orphan Process in Unix/Linux

    Add A Comment

    Leave A Reply Cancel Reply

    Advertisement
    Recent Posts
    • 20 Basic Linux Commands for the Beginners (Recommended)
    • tail Command in Linux with Examples
    • What is a Orphan Process in Unix/Linux
    • How To Display Warning Message to Unauthorized SSH Access
    • How to Set a Custom SSH Login Banner and MOTD
    Facebook Twitter Instagram Pinterest
    © 2023 Tecadmin.net. All Rights Reserved | Terms  | Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.