aws - 月账单计算

2024-09-07
import boto3
from botocore.session import Session
from datetime import datetime, timedelta
import calendar
import sys

# 从 ~/.aws/credentials 文件中读取凭证
#session = Session(profile="prod")
session = Session(profile=sys.argv[1])
credentials = session.get_credentials()

# 使用凭证创建AWS Cost Explorer客户端
ce = boto3.client('ce', aws_access_key_id=credentials.access_key, aws_secret_access_key=credentials.secret_key)


# 获取当前时间
now = datetime.now()

# 计算上个月的第一天
start_datetime = now.replace(day=1) - timedelta(days=1)
start_datetime = start_datetime.replace(day=1)
end_datetime = now.replace(day=1)

# 使用strftime方法将datetime对象转换为字符串
start_date = start_datetime.strftime('%Y-%m-%d')
end_date = end_datetime.strftime('%Y-%m-%d')

#start_date = '2024-05-01'
#end_date = '2024-06-01'

print("Start Date:", start_date)
print("End Date:", end_date)

# 定义要查询的区域和标签
regions = ["us-west-1", "us-west-2", "ap-southeast-1", "us-east-1", "global"]
tags = ["gpu-cloud", "faas", "infra-iaas", "bigdata", "platform", "g0-public", "security", "paas", "ka", "infra-cloud", "public", "ABSENT"]

# 初始化总金额字典
total_amounts = {
    "region": {},
    "tag": {},
    "region_tag": {}
}

# 获取地区纬度的总金额
for region in regions:
    response = ce.get_cost_and_usage(
        TimePeriod={
            'Start': start_date,
            'End': end_date
        },
        Granularity='MONTHLY',
        Metrics=['UnblendedCost'],
        Filter={
            "Dimensions": {
                "Key": "REGION",
                "Values": [region]
            }
        }
    )

    # 计算总金额
    total_amount = 0
    for result in response['ResultsByTime']:
        total_amount += float(result['Total']['UnblendedCost']['Amount'])

    # 更新总金额字典
    total_amounts["region"][region] = round(total_amount, 2)

# 获取地区+标签纬度的总金额
for region in regions:
    for tag in tags:
        filter_dict = {
            "And": [
                {
                    "Dimensions": {
                        "Key": "REGION",
                        "Values": [region]
                    }
                },
                {
                    "Tags": {
                        "Key": "team",
                    }
                }
            ]
        }

        if tag == "ABSENT":
            filter_dict["And"][1]["Tags"]["MatchOptions"] = ["ABSENT"]
        else:
            filter_dict["And"][1]["Tags"]["Values"] = [tag]

        response = ce.get_cost_and_usage(
            TimePeriod={
                'Start': start_date,
                'End': end_date
            },
            Granularity='MONTHLY',
            Metrics=['UnblendedCost'],
            Filter=filter_dict
        )
        # 计算总金额
        total_amount = 0
        for result in response['ResultsByTime']:
            total_amount += float(result['Total']['UnblendedCost']['Amount'])

        # 更新总金额字典
        region_tag_key = f"{region}_{tag}"
        total_amounts["region_tag"][region_tag_key] = round(total_amount, 2)

# 输出总金额为制表符分隔的文本格式
header = "Region\tTotal\tgpu-cloud\tfaas\tinfra-iaas\tbigdata\tplatform\tg0-public\tsecurity\tpaas\tka\tinfra-cloud\tpublic\tno tag"
print(header)
for region in regions:
    row = [region]
    row.append(total_amounts["region"].get(region, 0))
    for tag in tags:
        region_tag_key = f"{region}_{tag}"
        row.append(total_amounts["region_tag"].get(region_tag_key, 0))
    print("\t".join(map(str, row)))