How to get the On-Demand price of EC2 Instances using Python and Boto3


Last Updated on May 14, 2021

The Python code below gets the on-demand price (in USD) of the EC2 instance type t2.micro in the Asia Pacific (Mumbai) region with Linux operating system.

Note: There are more examples below where we get the hourly price of different on-demand EC2 Instances like other operating system or EC2 Instances that are running on Dedicated Instances or Dedicated Hosts.

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_ec2_instance_hourly_price(region_code, 
                                  instance_type, 
                                  operating_system, 
                                  preinstalled_software='NA', 
                                  tenancy='Shared', 
                                  is_byol=False):
                                       
    region_name = get_region_name(region_code)

    if is_byol:
        license_model = 'Bring your own license'
    else:
        license_model = 'No License required'

    if tenancy == 'Host':
        capacity_status = 'AllocatedHost'
    else:
        capacity_status = 'Used'
    
    filters = [
        {'Type': 'TERM_MATCH', 'Field': 'termType', 'Value': 'OnDemand'},
        {'Type': 'TERM_MATCH', 'Field': 'capacitystatus', 'Value': capacity_status},
        {'Type': 'TERM_MATCH', 'Field': 'location', 'Value': region_name},
        {'Type': 'TERM_MATCH', 'Field': 'instanceType', 'Value': instance_type},
        {'Type': 'TERM_MATCH', 'Field': 'tenancy', 'Value': tenancy},
        {'Type': 'TERM_MATCH', 'Field': 'operatingSystem', 'Value': operating_system},
        {'Type': 'TERM_MATCH', 'Field': 'preInstalledSw', 'Value': preinstalled_software},
        {'Type': 'TERM_MATCH', 'Field': 'licenseModel', 'Value': license_model},
    ]

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

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

        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-south-1'
    instance_type = 't2.micro'
    operating_system = 'Linux'


    ec2_instance_price = get_ec2_instance_hourly_price(
        region_code=region_code, 
        instance_type=instance_type, 
        operating_system=operating_system,
    )

    print(instance_type, operating_system, region_code)
    print(ec2_instance_price)

Output

t2.micro Linux ap-south-1
0.0124

You can check if the result is correct in AWS EC2 On-Demand Pricing page.


Code Explained

The get_ec2_instance_hourly_price uses the AWS Price List API of boto3.

The price changes based on different considerations like region, instance type and operating system for EC2 Instances. The get_ec2_instance_hourly_price takes these considerations as parameters and outputs the on-demand hourly price of an EC2 Instance as float.

If the parameters does not match any EC2 Instance on the given region then it will return None.

The parameters, its purpose and possible values are listed below.

region_code (string)

Takes the region in the format of the region code such as ap-south-1, us-east-1 or eu-west-1.

The region code is then converted to a format that the AWS Price List API accepts, before being used in the filters for boto3 pricing.

Possible values for region_code are as follows.

af-south-1
ap-east-1
ap-northeast-1
ap-northeast-2
ap-northeast-3
ap-south-1
ap-southeast-1
ap-southeast-2
ca-central-1
eu-central-1
eu-north-1
eu-south-1
eu-west-1
eu-west-2
eu-west-3
me-south-1
sa-east-1
us-east-1
us-east-2
us-west-1
us-west-2

instance_type (string)

The instance type of the EC2 Instance.

There are a lot of possible values and these increases almost every year. Possible values can be found here.

Note: Not all instance types can be found in all regions.

operating_system (string)

The operating system of the target EC2 Instance.

Possible values for operating_system.

Linux
Red Hat Enterprise Linux with HA
RHEL
SUSE
Windows

preinstalled_software (string)

This is for EC2 Instances that uses an EC2 Image (AMI) that has a preinstalled SQL Server.

Possible values

ValueDescription
NANo preinstalled software
SQL EntSQL Server Enterprise
SQL StdSQL Server Standard
SQL WebSQL Server Web Edition

By default this is set to NA, no preinstalled software.

tenancy (string)

For specifying the tenancy of the target EC2 Instance.

Possible values

ValuesTenancy Type
SharedShared Hardware
DedicatedDedicated Instance or single-tenant hardware
HostDedicated Host, an isolated server with configurations you can control

To learn more about EC2 Instance Tenancy, visit the AWS Documentation here.

is_byol (Boolean)

Checks to see if the target EC2 Instance price is for Bring your own license (BYOL).

Possible Values: True, False

By default is_byol is set to False.


More Examples to get the On-Demand Price of EC2 Instances

The examples below uses the get_ec2_instance_hourly_price function and the get_region_name functions to get the different on-demand price of an EC2 Instance.

Get the hourly price of a normal EC2 Instance Type (Shared)

if __name__ == "__main__":
    region_code = 'me-south-1'
    instance_type = 't3.nano'
    operating_system = 'Linux'


    ec2_instance_price = get_ec2_instance_hourly_price(
        region_code=region_code, 
        instance_type=instance_type, 
        operating_system=operating_system,
    )

    print(instance_type, operating_system, region_code)
    print(ec2_instance_price)

Output

t3.nano Linux me-south-1
0.0063

Get the hourly price of a previous generation EC2 Instance Type

if __name__ == "__main__":
    region_code = 'us-west-1'
    instance_type = 'c1.xlarge'
    operating_system = 'Linux'


    ec2_instance_price = get_ec2_instance_hourly_price(
        region_code=region_code, 
        instance_type=instance_type, 
        operating_system=operating_system,
    )

    print(instance_type, operating_system, region_code)
    print(ec2_instance_price)

Output

c1.xlarge Linux us-west-1
0.592

To check if the price for Previous Generation EC2 Instance Types is correct visit the AWS page about Previous Generation EC2 Instance Types.


Get the hourly price of a metal EC2 Instance Type

if __name__ == "__main__":
    region_code = 'ap-southeast-1'
    instance_type = 'm6g.metal'
    operating_system = 'Linux'


    ec2_instance_price = get_ec2_instance_hourly_price(
        region_code=region_code, 
        instance_type=instance_type, 
        operating_system=operating_system,
    )

    print(instance_type, operating_system, region_code)
    print(ec2_instance_price)

Output

m6g.metal Linux ap-southeast-1
3.072

Get the hourly price of an EC2 Instance that is using Windows Server with SQL Server Enterprise.

if __name__ == "__main__":
    region_code = 'us-east-2'
    instance_type = 'r5d.2xlarge'
    operating_system = 'Windows'
    preinstalled_software = 'SQL Ent'


    ec2_instance_price = get_ec2_instance_hourly_price(
        region_code=region_code, 
        instance_type=instance_type, 
        operating_system=operating_system,
        preinstalled_software=preinstalled_software
    )

    print(instance_type, operating_system, preinstalled_software, region_code)
    print(ec2_instance_price)

Output

r5d.2xlarge Windows SQL Ent us-east-2
3.944

Get the hourly price of an EC2 Instance that is using Linux with SQL Server Standard.

if __name__ == "__main__":
    region_code = 'ca-central-1'
    instance_type = 'x1e.8xlarge'
    operating_system = 'Linux'
    preinstalled_software = 'SQL Std'


    ec2_instance_price = get_ec2_instance_hourly_price(
        region_code=region_code, 
        instance_type=instance_type, 
        operating_system=operating_system,
        preinstalled_software=preinstalled_software
    )

    print(instance_type, operating_system, preinstalled_software, region_code)
    print(ec2_instance_price)

Output

x1e.8xlarge Linux SQL Std ca-central-1
11.174

Get the hourly price of an EC2 Instance running in Windows bring your own license (BYOL)

if __name__ == "__main__":
    region_code = 'ap-southeast-1'
    instance_type = 'm5.xlarge'
    operating_system = 'Windows'
    is_byol=True


    ec2_instance_price = get_ec2_instance_hourly_price(
        region_code=region_code, 
        instance_type=instance_type, 
        operating_system=operating_system,
        is_byol=is_byol
    )

    print(instance_type, operating_system, is_byol, region_code)
    print(ec2_instance_price)

Output

m5.xlarge Windows True ap-southeast-1
0.24

Get the hourly price of an EC2 Instance running SUSE Linux Enterprise Server (SLES)

if __name__ == "__main__":
    region_code = 'ap-south-1'
    instance_type = 'c4.large'
    operating_system = 'SUSE'


    ec2_instance_price = get_ec2_instance_hourly_price(
        region_code=region_code, 
        instance_type=instance_type, 
        operating_system=operating_system
    )

    print(instance_type, operating_system, region_code)
    print(ec2_instance_price)

Output

c4.large SUSE ap-south-1
0.2

Get the hourly price of an EC2 Instance running Red Hat Enterprise Linux (RHEL)

if __name__ == "__main__":
    region_code = 'af-south-1'
    instance_type = 'c5ad.xlarge'
    operating_system = 'RHEL'


    ec2_instance_price = get_ec2_instance_hourly_price(
        region_code=region_code, 
        instance_type=instance_type, 
        operating_system=operating_system,
    )

    print(instance_type, operating_system, region_code)
    print(ec2_instance_price)

Output

c5ad.xlarge RHEL af-south-1
0.294

Get the hourly price of an EC2 Instance running Red Hat Enterprise Linux with HA

if __name__ == "__main__":
    region_code = 'sa-east-1'
    instance_type = 'm6g.16xlarge'
    operating_system = 'Red Hat Enterprise Linux with HA'


    ec2_instance_price = get_ec2_instance_hourly_price(
        region_code=region_code, 
        instance_type=instance_type, 
        operating_system=operating_system,
    )

    print(instance_type, operating_system, region_code)
    print(ec2_instance_price)

Output

m6g.16xlarge Red Hat Enterprise Linux with HA sa-east-1
4.0818

Get the hourly price of a Dedicated Instance

if __name__ == "__main__":
    region_code = 'ap-northeast-3'
    instance_type = 'r4.2xlarge'
    operating_system = 'Linux'
    tenancy = 'Dedicated'

    ec2_instance_price = get_ec2_instance_hourly_price(
        region_code=region_code, 
        instance_type=instance_type, 
        operating_system=operating_system,
        tenancy=tenancy
    )

    print(instance_type, operating_system, tenancy, region_code)
    print(ec2_instance_price)

Output

r4.2xlarge Linux Dedicated ap-northeast-3
0.704

To check if the price for Dedicated Instances is correct visit the AWSpricing page about Dedicated Instances.


Get the hourly price of a Dedicate Host EC2 Instance

if __name__ == "__main__":
    region_code = 'ap-southeast-2'
    instance_type = 'r5'
    operating_system = 'Linux'
    tenancy = 'Host'

    ec2_instance_price = get_ec2_instance_hourly_price(
        region_code=region_code, 
        instance_type=instance_type, 
        operating_system=operating_system,
        tenancy=tenancy
    )

    print(instance_type, operating_system, tenancy, region_code)
    print(ec2_instance_price)

Output

r5 Linux Host ap-southeast-2
7.973

To check if the price for Dedicated Host EC2 Instance is correct visit the AWS pricing page for Dedicated Hosts.


Get the On-Demand EC2 Instance Price in All Regions

Using the listing of all regions in boto3, we can create a Python Script to get the price of a specific Instance Type and operating system across all regions.

The code below will print the hourly price of an m5.large instance running Linux for all regions. Regions are alphabetically sorted by their region codes.

if __name__ == "__main__":

    ec2_client = boto3.client('ec2')

    response = ec2_client.describe_regions(AllRegions=True)

    regions = response['Regions']

    region_code_list = []

    for region in regions:
        region_code = region['RegionName']
        region_code_list.append(region_code)

    region_code_list = sorted(region_code_list)

    for region_code in region_code_list:

        instance_type = 'm5.large'
        operating_system = 'Linux'

        ec2_instance_price = get_ec2_instance_hourly_price(
            region_code=region_code, 
            instance_type=instance_type, 
            operating_system=operating_system,
        )

        print(ec2_instance_price, '\t', instance_type, '\t', operating_system, '\t', region_code, '\t', get_region_name(region_code))

Output

0.127 	 m5.large 	 Linux 	 af-south-1 	    Africa (Cape Town)
0.132 	 m5.large 	 Linux 	 ap-east-1 	        Asia Pacific (Hong Kong)
0.124 	 m5.large 	 Linux 	 ap-northeast-1     Asia Pacific (Tokyo)
0.118 	 m5.large 	 Linux 	 ap-northeast-2     Asia Pacific (Seoul)
0.124 	 m5.large 	 Linux 	 ap-northeast-3     Asia Pacific (Osaka)
0.101 	 m5.large 	 Linux 	 ap-south-1 	    Asia Pacific (Mumbai)
0.12 	 m5.large 	 Linux 	 ap-southeast-1     Asia Pacific (Singapore)
0.12 	 m5.large 	 Linux 	 ap-southeast-2     Asia Pacific (Sydney)
0.107 	 m5.large 	 Linux 	 ca-central-1 	    Canada (Central)
0.115 	 m5.large 	 Linux 	 eu-central-1 	    EU (Frankfurt)
0.102 	 m5.large 	 Linux 	 eu-north-1 	    EU (Stockholm)
0.112 	 m5.large 	 Linux 	 eu-south-1 	    EU (Milan)
0.107 	 m5.large 	 Linux 	 eu-west-1 	        EU (Ireland)
0.111 	 m5.large 	 Linux 	 eu-west-2 	        EU (London)
0.112 	 m5.large 	 Linux 	 eu-west-3 	        EU (Paris)
0.118 	 m5.large 	 Linux 	 me-south-1 	    Middle East (Bahrain)
0.153 	 m5.large 	 Linux 	 sa-east-1 	        South America (Sao Paulo)
0.096 	 m5.large 	 Linux 	 us-east-1 	        US East (N. Virginia)
0.096 	 m5.large 	 Linux 	 us-east-2 	        US East (Ohio)
0.112 	 m5.large 	 Linux 	 us-west-1 	        US West (N. California)
0.096 	 m5.large 	 Linux 	 us-west-2 	        US West (Oregon)

I hope the above helps in getting the hourly price of on-demand EC2 Instances.


3 responses to “How to get the On-Demand price of EC2 Instances using Python and Boto3”

Leave a Reply

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