|
| 1 | +"""AWS EC2 instance pricing functionality. |
| 2 | +
|
| 3 | +This module provides functions to retrieve EC2 instance pricing information |
| 4 | +using the AWS Pricing API. |
| 5 | +""" |
| 6 | + |
| 7 | +import json |
| 8 | +from functools import lru_cache |
| 9 | +from typing import Any |
| 10 | + |
| 11 | +import boto3 |
| 12 | +from botocore.exceptions import ClientError, NoCredentialsError |
| 13 | + |
| 14 | +# AWS region to location name mapping |
| 15 | +# The Pricing API uses location names, not region codes |
| 16 | +REGION_TO_LOCATION: dict[str, str] = { |
| 17 | + "us-east-1": "US East (N. Virginia)", |
| 18 | + "us-east-2": "US East (Ohio)", |
| 19 | + "us-west-1": "US West (N. California)", |
| 20 | + "us-west-2": "US West (Oregon)", |
| 21 | + "eu-west-1": "Europe (Ireland)", |
| 22 | + "eu-west-2": "Europe (London)", |
| 23 | + "eu-west-3": "Europe (Paris)", |
| 24 | + "eu-central-1": "Europe (Frankfurt)", |
| 25 | + "eu-north-1": "Europe (Stockholm)", |
| 26 | + "ap-northeast-1": "Asia Pacific (Tokyo)", |
| 27 | + "ap-northeast-2": "Asia Pacific (Seoul)", |
| 28 | + "ap-northeast-3": "Asia Pacific (Osaka)", |
| 29 | + "ap-southeast-1": "Asia Pacific (Singapore)", |
| 30 | + "ap-southeast-2": "Asia Pacific (Sydney)", |
| 31 | + "ap-south-1": "Asia Pacific (Mumbai)", |
| 32 | + "sa-east-1": "South America (Sao Paulo)", |
| 33 | + "ca-central-1": "Canada (Central)", |
| 34 | +} |
| 35 | + |
| 36 | +# Hours per month (for calculating monthly estimates) |
| 37 | +HOURS_PER_MONTH = 730 |
| 38 | + |
| 39 | + |
| 40 | +@lru_cache(maxsize=1) |
| 41 | +def get_pricing_client() -> Any: |
| 42 | + """Get or create the Pricing client. |
| 43 | +
|
| 44 | + The Pricing API is only available in us-east-1 and ap-south-1. |
| 45 | + We use us-east-1 for consistency. |
| 46 | +
|
| 47 | + Returns: |
| 48 | + boto3 Pricing client instance |
| 49 | + """ |
| 50 | + return boto3.client("pricing", region_name="us-east-1") |
| 51 | + |
| 52 | + |
| 53 | +def get_current_region() -> str: |
| 54 | + """Get the current AWS region from the session. |
| 55 | +
|
| 56 | + Returns: |
| 57 | + The current AWS region code |
| 58 | + """ |
| 59 | + session = boto3.session.Session() |
| 60 | + return session.region_name or "us-east-1" |
| 61 | + |
| 62 | + |
| 63 | +@lru_cache(maxsize=256) |
| 64 | +def get_instance_price(instance_type: str, region: str | None = None) -> float | None: |
| 65 | + """Get the hourly on-demand price for an EC2 instance type. |
| 66 | +
|
| 67 | + Args: |
| 68 | + instance_type: The EC2 instance type (e.g., 't3.micro', 'm5.large') |
| 69 | + region: AWS region code. If None, uses the current session region. |
| 70 | +
|
| 71 | + Returns: |
| 72 | + The hourly price in USD, or None if pricing is unavailable. |
| 73 | +
|
| 74 | + Note: |
| 75 | + This function caches results to reduce API calls. |
| 76 | + Prices are for Linux on-demand instances with shared tenancy. |
| 77 | + """ |
| 78 | + if region is None: |
| 79 | + region = get_current_region() |
| 80 | + |
| 81 | + # Get location name for region |
| 82 | + location = REGION_TO_LOCATION.get(region) |
| 83 | + if not location: |
| 84 | + # Region not in our mapping, return None |
| 85 | + return None |
| 86 | + |
| 87 | + try: |
| 88 | + pricing_client = get_pricing_client() |
| 89 | + response = pricing_client.get_products( |
| 90 | + ServiceCode="AmazonEC2", |
| 91 | + Filters=[ |
| 92 | + {"Type": "TERM_MATCH", "Field": "instanceType", "Value": instance_type}, |
| 93 | + {"Type": "TERM_MATCH", "Field": "location", "Value": location}, |
| 94 | + {"Type": "TERM_MATCH", "Field": "operatingSystem", "Value": "Linux"}, |
| 95 | + {"Type": "TERM_MATCH", "Field": "tenancy", "Value": "Shared"}, |
| 96 | + {"Type": "TERM_MATCH", "Field": "preInstalledSw", "Value": "NA"}, |
| 97 | + {"Type": "TERM_MATCH", "Field": "capacitystatus", "Value": "Used"}, |
| 98 | + ], |
| 99 | + MaxResults=1, |
| 100 | + ) |
| 101 | + |
| 102 | + price_list = response.get("PriceList", []) |
| 103 | + if not price_list: |
| 104 | + return None |
| 105 | + |
| 106 | + # Parse the price from the response |
| 107 | + price_data = json.loads(price_list[0]) |
| 108 | + terms = price_data.get("terms", {}).get("OnDemand", {}) |
| 109 | + |
| 110 | + if not terms: |
| 111 | + return None |
| 112 | + |
| 113 | + # Get the first term and its price dimension |
| 114 | + for term in terms.values(): |
| 115 | + price_dimensions = term.get("priceDimensions", {}) |
| 116 | + for dimension in price_dimensions.values(): |
| 117 | + price_per_unit = dimension.get("pricePerUnit", {}).get("USD") |
| 118 | + if price_per_unit: |
| 119 | + return float(price_per_unit) |
| 120 | + |
| 121 | + return None |
| 122 | + |
| 123 | + except ClientError: |
| 124 | + # Don't raise an exception for pricing errors - just return None |
| 125 | + # Pricing failures shouldn't block the main functionality |
| 126 | + return None |
| 127 | + except NoCredentialsError: |
| 128 | + return None |
| 129 | + except (json.JSONDecodeError, KeyError, ValueError, TypeError): |
| 130 | + return None |
| 131 | + |
| 132 | + |
| 133 | +def get_monthly_estimate(hourly_price: float | None) -> float | None: |
| 134 | + """Calculate monthly cost estimate from hourly price. |
| 135 | +
|
| 136 | + Args: |
| 137 | + hourly_price: The hourly price in USD |
| 138 | +
|
| 139 | + Returns: |
| 140 | + The estimated monthly cost in USD, or None if hourly_price is None |
| 141 | + """ |
| 142 | + if hourly_price is None: |
| 143 | + return None |
| 144 | + return hourly_price * HOURS_PER_MONTH |
| 145 | + |
| 146 | + |
| 147 | +def format_price(price: float | None, prefix: str = "$") -> str: |
| 148 | + """Format a price for display. |
| 149 | +
|
| 150 | + Args: |
| 151 | + price: The price to format |
| 152 | + prefix: Currency prefix (default: "$") |
| 153 | +
|
| 154 | + Returns: |
| 155 | + Formatted price string, or "-" if price is None |
| 156 | + """ |
| 157 | + if price is None: |
| 158 | + return "-" |
| 159 | + if price < 0.01: |
| 160 | + return f"{prefix}{price:.4f}" |
| 161 | + return f"{prefix}{price:.2f}" |
| 162 | + |
| 163 | + |
| 164 | +def get_instance_pricing_info(instance_type: str, region: str | None = None) -> dict[str, Any]: |
| 165 | + """Get comprehensive pricing information for an instance type. |
| 166 | +
|
| 167 | + Args: |
| 168 | + instance_type: The EC2 instance type |
| 169 | + region: AWS region code. If None, uses the current session region. |
| 170 | +
|
| 171 | + Returns: |
| 172 | + Dictionary with 'hourly', 'monthly', and formatted strings |
| 173 | + """ |
| 174 | + hourly = get_instance_price(instance_type, region) |
| 175 | + monthly = get_monthly_estimate(hourly) |
| 176 | + |
| 177 | + return { |
| 178 | + "hourly": hourly, |
| 179 | + "monthly": monthly, |
| 180 | + "hourly_formatted": format_price(hourly), |
| 181 | + "monthly_formatted": format_price(monthly), |
| 182 | + } |
| 183 | + |
| 184 | + |
| 185 | +def clear_price_cache() -> None: |
| 186 | + """Clear the pricing cache. |
| 187 | +
|
| 188 | + Useful for testing or when you want to refresh pricing data. |
| 189 | + """ |
| 190 | + get_instance_price.cache_clear() |
0 commit comments