Search code examples
amazon-web-servicesboto3amazon-cloudwatch

boto3 method to get AWS billing


When I log into my AWS account and go to the Billing -> Bills dashboard, I see my Total Bill for the month and previous months, $X USD. Boto3's cost explorer will return my monthly AmortizedCost, but number returned is significantly less than my Total Bill?

def billing(account):
    today  = date.today()
    start  = today.replace(day = 1) - relativedelta(months = 12)

    client = boto3.client('ce',
                         region_name = 'us-east-1',
                         aws_access_key_id = 'aws_access_key_id',
                         aws_secret_access_key = 'aws_secret_access_key'

    response = client.get_cost_and_usage(
        TimePeriod={
           'Start': str(start),
           'End':   str(today),
        },
        Granularity = 'MONTHLY',
        Metrics=[
            'AmortizedCost',
            ]
    )

    print("{}".format(account['Account']))
    for item in response['ResultsByTime']:
        print("{}: {}".format( item['TimePeriod']['Start'], item['Total']['AmortizedCost']['Amount']))

How do I get the total amount I see on the Billing -> Bills dashboard?

I'm trying cloudwatch, but I'm not having any success.


Solution

  • Courtesy of the AWS support, the idea was that maybe there were refunds and credits being added which reduced the total. Adding the filters to NOT include refunds and credit produce the same results as on the Billing dashboard.

    def billing(account):
        today  = date.today()
        start  = today.replace(day = 1) - relativedelta(months = 12)
    
        client = boto3.client('ce',
                         region_name = 'us-east-1',
                         aws_access_key_id = 'aws_access_key_id',
                         aws_secret_access_key = 'aws_secret_access_key'
    
        response = client.get_cost_and_usage(
            TimePeriod={
               'Start': str(start),
               'End':   str(today),
            },
            Filter = { 
                'Not': { 
                    'Dimensions': {
                        'Key': "RECORD_TYPE",
                        'Values': ["Refund", "Credit"]
                     }
                 },
            },
            Granularity = 'MONTHLY',
            Metrics=[ 'AmortizedCost' ]
        )