How to get the price of EBS Snapshots using Boto3 and Python

The code below gets the price of an EBS Snapshots given the AWS Region using Python and Boto3.

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_ebs_snapshot_price(region_code):

    region_name = get_region_name(region_code)
    
    filters = [
        {'Type': 'TERM_MATCH', 'Field': 'productFamily', 'Value': "Storage Snapshot"},
        {'Type': 'TERM_MATCH', 'Field': 'location', 'Value': region_name},
        {'Type': 'TERM_MATCH', 'Field': 'storageMedia', 'Value': 'Amazon S3'}
    ]

    pricing_client = boto3.client('pricing', region_name='ap-south-1')
    
    response = pricing_client.get_products(ServiceCode='AmazonEC2', Filters=filters)

    if len(response['PriceList']) > 0:
        price = json.loads(response['PriceList'][0])

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


if __name__ == "__main__":
    region_code = 'ap-southeast-1'
    snapshot_price = get_ebs_snapshot_price(region_code)
    print(snapshot_price, '\t', region_code)

    region_code = 'sa-east-1'
    snapshot_price = get_ebs_snapshot_price(region_code)
    print(snapshot_price, '\t', region_code)

    region_code = 'eu-west-1'
    snapshot_price = get_ebs_snapshot_price(region_code)
    print(snapshot_price, '\t', region_code)

Output

Continue reading How to get the price of EBS Snapshots using Boto3 and Python