How to get the price of AWS Load Balancers using Boto3 and Python

Below is a Python Script that gets the price of AWS Elastic Load Balancers (ELB). This can retrieve prices for Classic, Application, Network and Gateway Load Balancers. It can also get the price of load balancers in AWS Outposts. See the different examples of how to use this Python code below.

import boto3
import json
from pkg_resources import resource_filename

def get_region_name(region_code):

    endpoint_file = resource_filename('botocore', 'data/endpoints.json')

    with open(endpoint_file, 'r') as f:
        endpoint_data = json.load(f)

    region_name = endpoint_data['partitions'][0]['regions'][region_code]['description']

    region_name = region_name.replace('Europe', 'EU')

    return region_name

def get_load_balancer_price(region_code, lb_product_family, is_outposts=False):

    price_details = {}

    region_name = get_region_name(region_code)

    if is_outposts:
        location_type = 'AWS Outposts'
        location_type = 'AWS Region'

    filters = [
        {'Type': 'TERM_MATCH', 'Field': 'locationType', 'Value': location_type},
        {'Type': 'TERM_MATCH', 'Field': 'location', 'Value': region_name},
        {'Type': 'TERM_MATCH', 'Field': 'productFamily', 'Value': lb_product_family},

    pricing_client = boto3.client('pricing', region_name='us-east-1')
    response = pricing_client.get_products(ServiceCode='AWSELB', Filters=filters)

    if len(response['PriceList']) == 0:
        return None

    for price in response['PriceList']:
        price = json.loads(price)

        usage_type = price['product']['attributes']['usagetype']

        for on_demand in price['terms']['OnDemand'].values():
            for price_dimensions in on_demand['priceDimensions'].values():
                price_value = float(price_dimensions['pricePerUnit']['USD'])

                if 'LoadBalancerUsage' in usage_type:
                    price_details['LoadBalancerUsage'] = price_value
                elif 'DataProcessing-Bytes' in usage_type:
                    price_details['DataProcessing-Bytes'] = price_value
                elif 'LCUUsage' in usage_type:
                    price_details['LCUUsage'] = price_value
    return price_details

if __name__ == "__main__":
    region_code = 'ap-south-1'
    lb_product_family = 'Load Balancer'    # Classic Load Balancer
    price_details = get_load_balancer_price(region_code, lb_product_family)

    print(region_code, lb_product_family)


Continue reading How to get the price of AWS Load Balancers using Boto3 and Python