所有实例的AWS成本和使用率

时间:2019-07-26 13:05:27

标签: amazon-web-services aws-lambda boto3

我想在一段时间内获取AWS帐户中每个实例的使用成本报告。

我能够在输出中获取linked_account_id和服务,但是我也需要instance_id。请帮助

import argparse
import boto3
import datetime

cd = boto3.client('ce', 'ap-south-1')

results = []

token = None
while True:
    if token:
        kwargs = {'NextPageToken': token}
    else:
        kwargs = {}
    data = cd.get_cost_and_usage(
    TimePeriod={'Start': '2019-01-01', 'End':  '2019-06-30'},
    Granularity='MONTHLY',
    Metrics=['BlendedCost','UnblendedCost'],
    GroupBy=[
                {'Type': 'DIMENSION', 'Key': 'LINKED_ACCOUNT'},
                {'Type': 'DIMENSION', 'Key': 'SERVICE'}
             ], **kwargs)
    results += data['ResultsByTime']
    token = data.get('NextPageToken')
    if not token:
        break
print('\t'.join(['Start_date', 'End_date', 'LinkedAccount', 'Service', 'blended_cost','unblended_cost', 'Unit', 'Estimated']))
for result_by_time in results:
    for group in result_by_time['Groups']:
        blended_cost = group['Metrics']['BlendedCost']['Amount']
        unblended_cost = group['Metrics']['UnblendedCost']['Amount']
        unit = group['Metrics']['UnblendedCost']['Unit']
        print(result_by_time['TimePeriod']['Start'], '\t',
        result_by_time['TimePeriod']['End'],'\t',
        '\t'.join(group['Keys']), '\t',
        blended_cost,'\t',
        unblended_cost, '\t',
        unit, '\t',
        result_by_time['Estimated'])

1 个答案:

答案 0 :(得分:1)

据我所知,Cost Explorer无法处理每个实例的使用情况。有一个功能成本和使用情况报告,该功能按转储文件提供详细的帐单报告。在此文件中,您可以看到实例ID。

它也可以连接到 AWS Athena 。完成此操作后,直接在Athena上查询文件。


这是我的例子。

select 
    lineitem_resourceid,
    sum(lineitem_unblendedcost) as unblended_cost,
    sum(lineitem_blendedcost) as blended_cost
from 
    <table>
where 
    lineitem_productcode = 'AmazonEC2' and 
    product_operation like 'RunInstances%'
group by 
    lineitem_resourceid

结果是

lineitem_resourceid     unblended_cost      blended_cost
i-*****************     279.424             279.424
i-*****************     139.948             139.948
i-********              68.198              68.198
i-*****************     3.848               3.848
i-*****************     0.013               0.013

其中resourceid包含实例ID。该月所有使用费用的总和为。对于其他类型的product_operation,它将包含不同的资源ID。