Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      Sunshine And March Vibes (2025 Wallpapers Edition)

      June 1, 2025

      The Case For Minimal WordPress Setups: A Contrarian View On Theme Frameworks

      June 1, 2025

      How To Fix Largest Contentful Paint Issues With Subpart Analysis

      June 1, 2025

      How To Prevent WordPress SQL Injection Attacks

      June 1, 2025

      My top 5 must-play PC games for the second half of 2025 — Will they live up to the hype?

      June 1, 2025

      A week of hell with my Windows 11 PC really makes me appreciate the simplicity of Google’s Chromebook laptops

      June 1, 2025

      Elden Ring Nightreign Night Aspect: How to beat Heolstor the Nightlord, the final boss

      June 1, 2025

      New Xbox games launching this week, from June 2 through June 8 — Zenless Zone Zero finally comes to Xbox

      June 1, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      Student Record Android App using SQLite

      June 1, 2025
      Recent

      Student Record Android App using SQLite

      June 1, 2025

      When Array uses less memory than Uint8Array (in V8)

      June 1, 2025

      Laravel 12 Starter Kits: Definite Guide Which to Choose

      June 1, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      My top 5 must-play PC games for the second half of 2025 — Will they live up to the hype?

      June 1, 2025
      Recent

      My top 5 must-play PC games for the second half of 2025 — Will they live up to the hype?

      June 1, 2025

      A week of hell with my Windows 11 PC really makes me appreciate the simplicity of Google’s Chromebook laptops

      June 1, 2025

      Elden Ring Nightreign Night Aspect: How to beat Heolstor the Nightlord, the final boss

      June 1, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»Setting up CloudFront using Python

    Setting up CloudFront using Python

    February 26, 2025

    Python is an open-source programming language, we can use python to build/enable the AWS services such as Terraform or other IAC code. In this blog we are going to discuss setting up the CloudFront service using Python.

    Why We Use Python:

    As we know, Python is an imperative language, it means that you can write more customized scripts that can perform advanced complex operations, handle errors, interact with Apis etc. And, you have access to AWS SDKs like Boto3 that allow you to perform any AWS operation you desire, including custom ones that might not yet to be supported by Terraform.

    How It Works:

    We have defined method and classes in boto3 library for AWS services that we can use to create/modify/update AWS services.

    Prerequisites:

    We require only Python and Boto3 library.

    1                                    Picture2                                  Picture3

     

    How to Write Code:

    As we know boto3 has different functions to handle AWS services, we have lots of functions but below mentioned are basic function to manage CloudFront service:

    • create_distribution is used to create CloudFront Distribution,
    • update_distribution is used to update CloudFront Distribution,
    • delete_distribution is used to delete CloudFront Distribution,
    • create_cache_policy is used to create cache policy,
    • create_invalidation is used to create invalidation requests.

    create_distribution, update_distribution required the lots configuration values as well, you can use python dictionary variable and can pass to function, or you can pass it as Json but you have to perform parsing as well for that.

    Let me share with you a basic example of creating CloudFront distribution using python & boto3:

    import boto3
    import os 
    
    s3_origin_domain_name = '<s3bucketname>.s3.amazonaws.com'  
    origin_id = 'origin-id'
    
    distribution_config = {
            'CallerReference': str(hash("unique-reference")),
            'Comment': 'My CloudFront Distribution',
            'Enabled': True,
            'Origins': {
                'Items': [
                    {
                        'Id': origin_id,
                        'DomainName': s3_origin_domain_name,
                        'S3OriginConfig': {
                            'OriginAccessIdentity': ''
                        },
                        'CustomHeaders': {
                            'Quantity': 0,
                            'Items': []
                        }
                    }
                ],
                'Quantity': 1
            },
            'DefaultCacheBehavior': {
                'TargetOriginId': origin_id,
                'ViewerProtocolPolicy': 'redirect-to-https',
                'AllowedMethods': {
                    'Quantity': 2,
                    'Items': ['GET', 'HEAD'],
                    'CachedMethods': {
                        'Quantity': 2,
                        'Items': ['GET', 'HEAD']
                    }
                },
                'ForwardedValues': {
                    'QueryString': False,
                    'Cookies': {
                        'Forward': 'none'
                    }
                },
                'MinTTL': 3600
            },
            'ViewerCertificate': {
                'CloudFrontDefaultCertificate': True
            },
            'PriceClass': 'PriceClass_100' 
        }
    try:
            aws_access_key = os.getenv('AWS_ACCESS_KEY_ID')
      aws_secret_key = os.getenv('AWS_SECRET_ACCESS_KEY')
            session = boto3.Session(
    aws_access_key_id=aws_access_key,
    aws_secret_access_key=aws_secret_key,
                 region_name='us-east-1'
              )
            client = session.client('cloudfront')
            response = client.create_distribution(DistributionConfig=distribution_config)
            print("CloudFront Distribution created successfully!")
            print(response)
    except Exception as e:
            print(f"Error creating CloudFront distribution: {e}")
    

    As you can see above sample code after importing boto3 module we have taken distribution_config variable where all the configs stored after that we call create_dirtibution function to cdn distribution:

            response = client.create_distribution(DistributionConfig=distribution_config)

    So, like Similar way you can write the more complex python code to implement your complex AWS infrastructure as well and do automation for setting up cache invalidation request pipeline, that will give user a functionality as well as clear cdn cache without logging in AWS console.

    Source: Read More 

    Facebook Twitter Reddit Email Copy Link
    Previous ArticleFrom Cloud to Local: Effortlessly Import Azure SQL Databases
    Next Article Windows Password Recovery with AWS SSM

    Related Posts

    Security

    New Linux Flaws Allow Password Hash Theft via Core Dumps in Ubuntu, RHEL, Fedora

    June 1, 2025
    Security

    DevSecOps Phase 4B: Manual Penetration Testing

    June 1, 2025
    Leave A Reply Cancel Reply

    Continue Reading

    New URLPattern API brings improved pattern matching

    Development

    Quick Glossary: Web Browsers

    Development

    Copilot+ certified hardware Galaxy Book4 Edge has finally arrived in US, UK, & more for $1,349

    Development

    “ConfusedComposer”: GCP Composer Vulnerability Allows Privilege Escalation

    Security

    Highlights

    How to Better Protect Your Intellectual Property

    February 11, 2025

    Intellectual property law is designed to protect ideas and unique products from the threat of…

    Improving Content Moderation with Amazon Rekognition Bulk Analysis and Custom Moderation

    April 5, 2024

    Windows 11 25H2 Update: Minor Changes Expected in October 2025

    April 28, 2025

    No Matter How You Package It, Apple Intelligence Is AI

    June 14, 2024
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

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