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 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. This means that you can write more customized scripts that can perform advanced complex operations, handle errors, interact with APIs, etc. You also have access to AWS SDKs like Boto3 that allow you to perform any AWS operation you desire, including custom ones that might not yet be supported by Terraform.

How It Works

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

Prerequisites

We require only Python and Boto3 library.

1                                                                      Picture3

 

How to Write Code

As we know, boto3 has different functions that handle AWS services. We have lots of functions, but below are the basic functions 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 and update_distribution require the lots configuration values as well. You can use a Python dictionary variable and pass it to a 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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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}")
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}")
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 in the above sample code, after importing the boto3 module, we have the distribution_config variable where all the configs are stored. After that, we call the  create_dirtibution function to cdn distribution:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
response = client.create_distribution(DistributionConfig=distribution_config)
response = client.create_distribution(DistributionConfig=distribution_config)
        response = client.create_distribution(DistributionConfig=distribution_config)

So, in a similar way, you can write more complex Python code to implement your complex AWS infrastructure as well and automate setting up a cache invalidation request pipeline, which will give users functionality and allow them to clear CDN cache without logging in to the 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