如何使用boto3检查对“成本和使用情况报告”选项卡的访问

2024-09-28 05:23:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将AWS boto3用于我的应用程序。 在查看boto3文档后,我找不到计费API。 我的应用程序的目的是检查我是否可以访问成本和使用情况报告。 如果我没有(如图中所示),我希望脚本通知我: enter image description here

我怎么检查?我使用的凭据是我在担任角色后获得的凭据 我尝试了以下方法:

costExplorer = boto3.client(
    'ce',
    aws_access_key_id=credentials['AccessKeyId'],
    aws_secret_access_key=credentials['SecretAccessKey'],
    aws_session_token=credentials['SessionToken']
)

endTime = datetime.now(timezone.utc)
if endTime.month == 1:
    startTime = datetime(endTime.year - 1, endTime.month + 11, endTime.day)
else:
    startTime = datetime(endTime.year, endTime.month - 1, endTime.day)

timePeriod: Dict[str, str] = {
    'Start': startTime.strftime("%Y-%m-%d"),
    'End': endTime.strftime("%Y-%m-%d")
}
# if it raise exception -> Means I don't have access to the Cost & Usage Reports tab
costExplorer.get_cost_and_usage(TimePeriod=timePeriod, Metrics=["UsageQuantity"])

此代码在我没有访问权限时有效,但在我确实有访问权限时也会引发异常


Tags: keyaws应用程序datetimeifaccessboto3year

热门问题