You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Boto3获取AWS账单控制台显示的月度总账单金额?

解决Cost Explorer与Billing控制台账单金额不一致的问题

问题原因

你看到的差异核心在于AmortizedCost是摊销后成本——它会把预付类费用(比如预留实例的预付金)分摊到多个使用月份;而Billing控制台显示的总账单是当月实际发生的所有费用,包含一次性支付的费用(如预付RI费用、支持计划费、税费等),所以两者数值会有明显差距。

解决方案

1. 替换核心指标为UnblendedCost

UnblendedCost对应控制台显示的实际月度费用,包含所有一次性支付和实时产生的费用,是最贴近控制台总账单金额的指标。

2. 调整时间范围确保数据完整

Cost Explorer的End日期是排他的,若要获取完整月度账单,需将End设为下月1号(比如9月账单的End设为2024-10-01),避免因设置为当前日期导致数据不完整。

3. 修正代码语法问题

原代码中boto3.client初始化缺少右括号,需补上才能正常运行。

修改后的代码

from datetime import date
from dateutil.relativedelta import relativedelta
import boto3

def billing(account):
    today = date.today()
    # 起始时间:12个月前的当月1号
    start = today.replace(day=1) - relativedelta(months=12)
    # 结束时间:下月1号,确保覆盖整月数据;若需截止到当前日期,可改为str(today)
    end = today.replace(day=1) + relativedelta(months=1)

    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(end),
        },
        Granularity='MONTHLY',
        # 包含与控制台账单相关的核心指标
        Metrics=[
            'UnblendedCost',
            'Tax',
            'Support'
        ]
    )

    print(f"{account['Account']}")
    for item in response['ResultsByTime']:
        period_start = item['TimePeriod']['Start']
        period_end = item['TimePeriod']['End']
        print(f"\n{period_start} 至 {period_end}:")
        print(f"  基础费用: {item['Total']['UnblendedCost']['Amount']} {item['Total']['UnblendedCost']['Unit']}")
        if 'Tax' in item['Total']:
            print(f"  税费: {item['Total']['Tax']['Amount']} {item['Total']['Tax']['Unit']}")
        if 'Support' in item['Total']:
            print(f"  支持计划费用: {item['Total']['Support']['Amount']} {item['Total']['Support']['Unit']}")
        # 计算控制台显示的总账单:基础费用+税费+支持费用
        total_bill = float(item['Total']['UnblendedCost']['Amount'])
        if 'Tax' in item['Total']:
            total_bill += float(item['Total']['Tax']['Amount'])
        if 'Support' in item['Total']:
            total_bill += float(item['Total']['Support']['Amount'])
        print(f"  控制台对应总账单金额: {round(total_bill, 2)} USD")

额外说明

  • 如果需要获取控制台的应付金额(Amount Due),还需加入Credit和Refund指标,计算时减去这些减免项。
  • 确保IAM用户拥有ce:GetCostAndUsage权限,否则无法获取数据。
  • Cost Explorer的数据存在1-2天的延迟,若查看当月实时账单,可能与控制台有微小差异。

内容的提问来源于stack exchange,提问作者user2569618

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 10:55:50