0
reservations = client.describe_instances()['Reservations']

I have used describeinstances() to get instance id to get of every instances first.Is there a way to use get_cost_and_usage() to get price of every instance using instance id using this function?

Luff li
  • 123
  • 2
  • 11
  • Does this answer your question? [Use boto3 to get current price for given EC2 instance type](https://stackoverflow.com/questions/51673667/use-boto3-to-get-current-price-for-given-ec2-instance-type) – PApostol Feb 13 '21 at 17:30
  • Are you hoping to determine the hourly cost for a specific instance type, or the total cost to date for a specific EC2 instance? – jarmod Feb 13 '21 at 17:40
  • @jarmod the total cost to date for a specific EC2 instance using instance id. – Luff li Feb 13 '21 at 17:49
  • The total cost, or the cost of the instance? The instance may do things (use resources in other S3 services, EBS, bandwidth, etc) that will add to the cost of running it. – Anon Coward Feb 13 '21 at 17:53
  • The total cost of the instance in specific date range. – Luff li Feb 13 '21 at 17:58
  • 2
    Cost Explorer may be a good option. You can report/visualize costs by service & region, and then filter on date range, resource types, tags etc. This won't, afaik, get you to a specific EC2 instance ID, but it may be helpful. – jarmod Feb 13 '21 at 18:04

2 Answers2

0

For me it helped to add an individual tag to the instances (e.g. Id) and then group by that tag:

response = client.get_cost_and_usage(
    TimePeriod={
        'Start': 'string',
        'End': 'string'
    },
    Granularity='DAILY'',
    Metrics=['BlendedCost','UnblendedCost'],
    GroupBy=[
        {
            'Type': 'TAG',
            'Key': 'Id'
        },
    ],
    NextPageToken='string'
)
Rene B.
  • 6,557
  • 7
  • 46
  • 72
-1

You can write some code to calculate that, there is no direct API available to calculate by instance id.

What you can do is combine various API calls:

  1. You can use DescribeServices , you get all the attributes of the all the services or if you want to have for one particular you can provide the name. Boto3 call describe_services

Returns the metadata for one service or a list of the metadata for all services

response = client.describe_services(
    FormatVersion='aws_v1',
    MaxResults=1,
    ServiceCode='AmazonEC2',
)

Above call gives you the necessary attributes you want to create filters for the next step


{
    'FormatVersion': 'aws_v1',
    'NextToken': 'abcdefg123',
    'Services': [
        {
            'AttributeNames': [
                'volumeType',
                'maxIopsvolume',
                'instanceCapacity10xlarge',
                'locationType',
                'operation',
            ],
            'ServiceCode': 'AmazonEC2',
        },
    ],
    'ResponseMetadata': {
        '...': '...',
    },
}
  1. Then you need to use GetAttributeValues to determine the possible values of the attributes. Boto3 call get_attribute_values
response = client.get_attribute_values(
    AttributeName='volumeType',
    MaxResults=2,
    ServiceCode='AmazonEC2',
)

print(response)
{
    'AttributeValues': [
        {
            'Value': 'Throughput Optimized HDD',
        },
        {
            'Value': 'Provisioned IOPS',
        },
    ],
    'NextToken': '',
    'ResponseMetadata': {
        '...': '...',
    },
}
  1. And finally depending on the attributes collected in the earlier step you can build a filter for get_producs
FLT = '[{{"Field": "tenancy", "Value": "shared", "Type": "TERM_MATCH"}},'\
      '{{"Field": "operatingSystem", "Value": "{o}", "Type": "TERM_MATCH"}},'\
      '{{"Field": "preInstalledSw", "Value": "NA", "Type": "TERM_MATCH"}},'\
      '{{"Field": "instanceType", "Value": "{t}", "Type": "TERM_MATCH"}},'\
      '{{"Field": "location", "Value": "{r}", "Type": "TERM_MATCH"}},'\
      '{{"Field": "capacitystatus", "Value": "Used", "Type": "TERM_MATCH"}}]'
    
data = client.get_products(ServiceCode='AmazonEC2', Filters=json.loads(f))
  1. Once you have the price of the instance depending on your instance start time, you just have to do simple multiplication to get the total cost.

Use boto3 to price for given EC2 instance type

get ec2 pricing programmatically?

samtoddler
  • 8,463
  • 2
  • 26
  • 21