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

如何在Azure资源图Explorer的Kusto查询中调用Cost Management API获取资源近30天成本?

问题解答

核心结论

Azure Resource Graph(ARG)本身不包含Cost Management的成本计费数据,因此无法直接在ARG Explorer中通过Kusto查询为资源关联过去30天的成本数据。ARG的数据集仅覆盖资源元数据、配置信息等,成本数据属于单独的Cost Management服务数据源。

可行的实现方案

1. 通过Azure Workbooks关联数据(最便捷)

你提到的Workbooks是最直接的方式,具体操作步骤如下:

  • 在Workbooks中添加「Resource Graph查询」组件,运行你的Kusto查询(建议补充输出id字段,用于关联成本数据):
    ResourceContainers
    | where type=='microsoft.resources/subscriptions/resourcegroups' 
    | project id, name, type  
    | limit 5
    | union  (Resources | project id, name, type | limit 5)
    
  • 添加「Cost Management查询」组件,设置时间范围为「过去30天」,查询维度选择「ResourceId」,聚合指标选择「总成本」,获取每个资源ID对应的成本数据
  • 使用Workbooks的「合并数据集」功能,通过id字段(资源ID)将两个组件的结果关联,最终展示资源名称、类型、过去30天成本

2. 通过脚本/API组合实现

如果需要自动化或批量处理,可以用PowerShell/CLI结合Cost Management API完成:

  • 第一步:运行ARG查询导出资源列表(以PowerShell为例):
    $resources = Search-AzGraph -Query @"
    ResourceContainers
    | where type=='microsoft.resources/subscriptions/resourcegroups' 
    | project id, name, type  
    | limit 5
    | union  (Resources | project id, name, type | limit 5)
    "@
    
  • 第二步:遍历资源列表,调用Cost Management API获取每个资源的过去30天成本:
    $startDate = (Get-Date).AddDays(-30).ToString("yyyy-MM-dd")
    $endDate = (Get-Date).ToString("yyyy-MM-dd")
    foreach ($res in $resources) {
        $costQuery = @{
            type = "ActualCost"
            timeframe = "Custom"
            timePeriod = @{ start = $startDate; end = $endDate }
            dataset = @{
                granularity = "Daily"
                aggregation = @{ totalCost = @{ name = "PreTaxCost"; function = "Sum" } }
                filter = @{
                    and = @(
                        @{ dimension = @{ name = "ResourceId"; operator = "In"; values = @($res.id) } }
                    )
                }
            }
        }
        $costResult = Invoke-AzCostManagementQuery -Scope "/subscriptions/<你的订阅ID>" -Query $costQuery
        # 合并资源信息与成本数据
        $res | Add-Member -NotePropertyName "TotalCost" -NotePropertyValue ($costResult.Properties.Rows | Measure-Object -Sum | Select-Object -ExpandProperty Sum)
    }
    # 输出结果
    $resources | Select-Object name, type, TotalCost
    

3. 自动化数据同步

如果需要长期查询,可以用Logic Apps或Azure Functions定期同步ARG资源数据和Cost Management数据到Azure Data Explorer(ADX)或存储账户,之后直接在ADX中用Kusto查询关联后的数据集。

关于在ARG Explorer中调用Cost Management API

ARG Explorer仅支持运行基于ARG数据集的Kusto查询,不支持直接调用外部API(包括Cost Management API)。所有需要关联成本数据的场景,都需要通过上述跨服务的方式实现。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 13:10:44