Python is an open-source programming language. We will use Python to construct/allow AWS companies akin to Terraform or different IAC code. On this weblog, we’re going to talk about organising the CloudFront service utilizing Python.

Why We Use Python

As we all know, Python is an crucial language. This implies which you could write extra custom-made scripts that may carry out superior complicated operations, deal with errors, work together with APIs, and so on. You even have entry to AWS SDKs like Boto3 that can help you carry out any AWS operation you need, together with customized ones which may not but be supported by Terraform.

How It Works

We now have outlined strategies and lessons within the boto3 library for AWS companies that we will use to create/modify/replace AWS companies.

Conditions

We require solely Python and Boto3 library.

1                                                                      Picture3

 

Tips on how to Write Code

As we all know, boto3 has completely different features that deal with AWS companies. We now have a number of features, however beneath are the fundamental features to handle CloudFront service:

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

create_distribution and update_distribution require the heaps configuration values as effectively. You need to use a Python dictionary variable and cross it to a operate, or you’ll be able to cross it as JSON, however it’s important to carry out parsing as effectively for that.

Let me share with you a primary instance of making CloudFront distribution utilizing Python & boto3:

import boto3
import os 

s3_origin_domain_name=".s3.amazonaws.com"  
origin_id = 'origin-id'

distribution_config = {
        'CallerReference': str(hash("unique-reference")),
        'Remark': 'My CloudFront Distribution',
        'Enabled': True,
        'Origins': {
            'Gadgets': [
                {
                    'Id': origin_id,
                    'DomainName': s3_origin_domain_name,
                    'S3OriginConfig': {
                        'OriginAccessIdentity': ''
                    },
                    'CustomHeaders': {
                        'Quantity': 0,
                        'Items': []
                    }
                }
            ],
            'Amount': 1
        },
        'DefaultCacheBehavior': {
            'TargetOriginId': origin_id,
            'ViewerProtocolPolicy': 'redirect-to-https',
            'AllowedMethods': {
                'Amount': 2,
                'Gadgets': ['GET', 'HEAD'],
                'CachedMethods': {
                    'Amount': 2,
                    'Gadgets': ['GET', 'HEAD']
                }
            },
            'ForwardedValues': {
                'QueryString': False,
                'Cookies': {
                    'Ahead': 'none'
                }
            },
            'MinTTL': 3600
        },
        'ViewerCertificate': {
            'CloudFrontDefaultCertificate': True
        },
        'PriceClass': 'PriceClass_100' 
    }
strive:
        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"
          )
        shopper = session.shopper('cloudfront')
        response = shopper.create_distribution(DistributionConfig=distribution_config)
        print("CloudFront Distribution created efficiently!")
        print(response)
besides Exception as e:
        print(f"Error creating CloudFront distribution: {e}")

As you’ll be able to see within the above pattern code, after importing the boto3 module, we now have the distribution_config variable the place all of the configs are saved. After that, we name the  create_dirtibution operate to cdn distribution:

        response = shopper.create_distribution(DistributionConfig=distribution_config)

So, in the same method, you’ll be able to write extra complicated Python code to implement your complicated AWS infrastructure as effectively and automate organising a cache invalidation request pipeline, which can give customers performance and permit them to clear CDN cache with out logging in to the AWS console.





Supply hyperlink

Categories: Digital Solution

Leave a Comment