如何使用Ruby获取Azure订阅总费用?
用Ruby获取Azure订阅费用的可行方案
Azure::Armrest库确实没有直接封装获取订阅总费用的方法,但你可以通过调用Azure Cost Management API来实现这个需求,以下是具体步骤:
1. 配置Azure权限
确保你的服务主体(Service Principal)拥有Cost Management Reader或更高权限(比如Contributor),这样才能调用Cost Management的查询接口。
2. 使用Ruby调用Cost Management API
你可以用Ruby的HTTP客户端(比如Net::HTTP或Faraday)直接发送请求,核心是先获取Azure ARM的访问令牌,再调用费用查询接口。
示例代码(基于Faraday)
require 'faraday' require 'json' # 替换为你的Azure服务主体及订阅信息 tenant_id = "你的租户ID" client_id = "你的客户端ID" client_secret = "你的客户端密钥" subscription_id = "你的订阅ID" # 第一步:获取ARM访问令牌 token_url = "https://login.microsoftonline.com/#{tenant_id}/oauth2/token" token_params = { grant_type: "client_credentials", client_id: client_id, client_secret: client_secret, resource: "https://management.azure.com/" } token_response = Faraday.post(token_url, token_params) token_data = JSON.parse(token_response.body) access_token = token_data["access_token"] # 第二步:调用Cost Management API查询总费用 cost_api_url = "https://management.azure.com/subscriptions/#{subscription_id}/providers/Microsoft.CostManagement/query?api-version=2023-11-01" query_body = { type: "ActualCost", timeframe: "TheLastMonth", # 可替换为自定义时间段 dataset: { aggregation: { totalCost: { name: "PreTaxCost", function: "Sum" } } } } cost_response = Faraday.post( cost_api_url, query_body.to_json, { "Authorization" => "Bearer #{access_token}", "Content-Type" => "application/json" } ) cost_data = JSON.parse(cost_response.body) total_cost = cost_data["properties"]["rows"][0][0] puts "订阅总费用:#{total_cost} 美元" # 币种取决于你的订阅配置
3. 自定义查询维度
你可以调整请求参数来获取更精细的费用数据:
- 指定自定义时间段:将
timeframe设为"Custom",同时添加timePeriod字段:"timePeriod": { "start": "2024-01-01", "end": "2024-01-31" } - 按资源组/服务类型拆分:在
dataset中添加grouping配置,按ResourceGroup或ServiceName分组统计。
内容的提问来源于stack exchange,提问作者user630702
相关产品推荐
相关产品推荐

