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

调用getcostandusage遇AccessDeniedException,Lambda权限配置后仍报错求方案

问题:调用get_cost_and_usage时触发AccessDeniedException错误

调用AWS Cost Explorer的get_cost_and_usage操作时出现AccessDeniedException,提示Lambda函数对应的角色未启用Cost Explorer访问权限。但已经为Lambda函数的IAM角色附加了所有所需权限,请问该如何解决?

问题代码

import boto3
import datetime
from tabulate import tabulate

def lambda_handler(event, context):
    # 初始化账单客户端
    client = boto3.client('ce', region_name='ap-south-1')

    # 设置账单报告的起始和结束日期
    start_date = datetime.date.today().replace(day=1)
    end_date = datetime.date.today()

    # 设置报告粒度
    granularity = 'DAILY'

    # 设置报告指标
    metric = 'BlendedCost'

    # 设置报告分组参数
    group_by = [
        {
            'Type': 'DIMENSION',
            'Key': 'SERVICE'
        }
    ]

    # 获取账单报告
    response = client.get_cost_and_usage(
        TimePeriod={
            'Start': start_date.strftime('%Y-%m-%d'),
            'End': end_date.strftime('%Y-%m-%d')
        },
        Granularity=granularity,
        Metrics=[metric],
        GroupBy=group_by
    )

    # 解析响应,提取服务名称和成本
    services = {}
    for result in response['ResultsByTime']:
        for group in result['Groups']:
            service_name = group['Keys'][0]
            cost = group['Metrics'][metric]['Amount']
            if service_name in services:
                services[service_name] += cost
            else:
                services[service_name] = cost

    # 生成服务成本表格
    data = []
    for service_name, cost in services.items():
        data.append([service_name, cost])
    table = tabulate(data, headers=["Service", "Cost"], tablefmt="pretty")
    print(table)
    # 返回账单报告响应
    response = {
        'statusCode': 200,
        'headers': {
            'Content-Type': 'text/plain',
            'Access-Control-Allow-Origin': '*'
        },
        'body': table
    }
    return response

解决办法

  • 确认Cost Explorer服务已启用:AWS账户默认可能未开启Cost Explorer,需手动在Cost Management控制台启用。操作路径:Cost Management控制台 → Cost Explorer → 点击「启用Cost Explorer」(若未开启)。
  • 验证IAM角色权限策略:确保Lambda角色的权限策略包含ce:GetCostAndUsage动作,且资源配置正确。示例策略如下:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "ce:GetCostAndUsage",
            "Resource": "*"
        }
    ]
}
  • 检查权限边界限制:如果Lambda角色设置了权限边界,必须确保边界策略同样允许ce:GetCostAndUsage动作,否则会覆盖附加的权限策略。
  • 确认角色信任关系:Lambda角色的信任关系必须允许lambda.amazonaws.com扮演该角色,正确的信任策略示例:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Service": "lambda.amazonaws.com"
            },
            "Action": "sts:AssumeRole"
        }
    ]
}
  • 调整区域配置:Cost Explorer属于全局服务,代码中指定的ap-south-1区域可能存在访问限制,可尝试移除region_name参数,使用boto3默认的全局端点。
  • 等待权限生效:IAM权限变更通常需要1-5分钟才能完全生效,刚添加权限后可等待片刻再测试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 17:08:11