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

      Sunshine And March Vibes (2025 Wallpapers Edition)

      June 3, 2025

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

      June 3, 2025

      How To Fix Largest Contentful Paint Issues With Subpart Analysis

      June 3, 2025

      How To Prevent WordPress SQL Injection Attacks

      June 3, 2025

      All the WWE 2K25 locker codes that are currently active

      June 3, 2025

      PSA: You don’t need to spend $400+ to upgrade your Xbox Series X|S storage

      June 3, 2025

      UK civil servants saved 24 minutes per day using Microsoft Copilot, saving two weeks each per year according to a new report

      June 3, 2025

      These solid-state fans will revolutionize cooling in our PCs and laptops

      June 3, 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

      Community News: Latest PECL Releases (06.03.2025)

      June 3, 2025
      Recent

      Community News: Latest PECL Releases (06.03.2025)

      June 3, 2025

      A Comprehensive Guide to Azure Firewall

      June 3, 2025

      Test Job Failures Precisely with Laravel’s assertFailedWith Method

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

      All the WWE 2K25 locker codes that are currently active

      June 3, 2025
      Recent

      All the WWE 2K25 locker codes that are currently active

      June 3, 2025

      PSA: You don’t need to spend $400+ to upgrade your Xbox Series X|S storage

      June 3, 2025

      UK civil servants saved 24 minutes per day using Microsoft Copilot, saving two weeks each per year according to a new report

      June 3, 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

    BitoPro Silent on $11.5M Hack: Investigator Uncovers Massive Crypto Theft

    June 3, 2025
    Security

    New Linux Vulnerabilities

    June 3, 2025
    Leave A Reply Cancel Reply

    Continue Reading

    Meet Genesis: An Open-Source Physics AI Engine Redefining Robotics with Ultra-Fast Simulations and Generative 4D Worlds

    Development

    Google AI Introduces Parfait: A Privacy-First AI System for Secure Data Aggregation and Analytics

    Machine Learning

    Bill Gates predicts “we will all have an AI agent” helping us prioritize what deserves our attention

    News & Updates

    Cisco Confirms Salt Typhoon Exploited CVE-2018-0171 to Target U.S. Telecom Networks

    Development

    Highlights

    Bouncer chooses the correct firewall zone for wireless connections

    June 1, 2025

    When you connect to a new network, Bouncer will open a window prompting you for…

    CVE-2025-5081 – Campcodes Cybercafe Management System SQL Injection Vulnerability

    May 22, 2025

    DOOM: The Dark Ages review and Metacritic score roundup — Does Xbox have its GOTY contender with this long-awaited shooter?

    May 10, 2025

    README

    August 12, 2024
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

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