Skip to main content

Cloud

Setting up CloudFront using Python

Coding See Through

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Ankit Srivastava

Ankit Kumar Srivastava is a Lead Technical Consultant at Perficient. He has 8 years of experience in AEM DevOps and Administration, Microsoft Bitlocker Administration and Monitoring (MBAM), and cloud technology. He is always keen to learn about new technologies!

More from this Author

Follow Us