Azure Cost Management - Forecast Rest API

spaceman sp 16 Reputation points
2022-07-28T18:35:53.387+00:00

In the Azure Portal under Cost Management, Cost Analysis, the Actual Cost and Forecast amounts are displayed. I want to get the forecast amount using the rest API and power shell. I have looked at the Forecast documentation and similar posts on stackoverflow but getting nowhere. I have a ticket open with Microsoft since late May 2022, but they have not been helpful.
Here is what I am doing:

I have a file called jsonfile.txt :

{  
  type: "Usage",  
  dataset: {  
    "granularity": "monthly",  
    "aggregation":{  
      "totalCost":{  
        "name":"Cost",  
        "function":"Sum"  
      }  
    }  
  },  
  timeframe: "MonthToDate"  
}  

I am not sure that this is the correct format for the file, am I missing anything?

I put that into the $body variable :

     $body = Get-Content .\jsonfile2.txt -Raw  

Log in and get the subscription ID ($subID) and token on the PS command line:

    $azContext = Get-AzContext -ErrorAction SilentlyContinue  
    $subID = $azContext.Subscription.id  

    $azProfile = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile  
    $profileClient = New-Object -TypeName Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient -ArgumentList ($azProfile)  
    $token = $profileClient.AcquireAccessToken($azContext.Subscription.TenantId)  
    $authHeader = @{  
                    'Content-Type'='application/json'  
                    'Authorization'='Bearer ' + $token.AccessToken  
    }  

Set the URL :

 $forecasturi =  "https://management.azure.com/subscriptions/$subid/providers/Microsoft.CostManagement/forecast?api-version=2021-10-01"  

then call the URL with header, method and body :

$theFC = invoke-restmethod  -uri $forecasturi -Method post -headers $authHeader -body $body  

and I just get this error:

invoke-restmethod : {"error":{"code":"BadRequest","message":"Invalid query definition: Invalid dataset grouping: 'BillingPeriod'; valid values: 'ResourceGroup','ResourceGroupName','ResourceType','ResourceI
d','ResourceLocation','SubscriptionId','SubscriptionName','MeterCategory','MeterSubcategory','Meter','ServiceFamily','UnitOfMeasure','PartNumber','BillingAccountName','BillingProfileId','BillingProfileName
','InvoiceSection','InvoiceSectionId','InvoiceSectionName','Product','ResourceGuid','ChargeType','ServiceName','ProductOrderId','ProductOrderName','PublisherType','ReservationId','ReservationName','Frequen
cy','InvoiceId','PricingModel','CostAllocationRuleName','MarkupRuleName','BillingMonth','Provider','BenefitId','BenefitName','CustomerTenantId','CustomerTenantDomainName','ResellerMPNId','PartnerEarnedCred
itApplied','CustomerName','PartnerName',''.\r\n\r\n (Request ID: 66c872c6-57af-4741-92bb-a5130ceae505)"}}
At line:1 char:10

  • $theFC = invoke-restmethod -uri $forecasturi -Method post -headers $ ...
  • ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  • CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
  • FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

I tried this, https://stackoverflow.com/questions/69821974/forecast-cost-azure-api, but no luck.
Any help would be appreciated.

Azure Cost Management
Azure Cost Management
A Microsoft offering that enables tracking of cloud usage and expenditures for Azure and other cloud providers.
3,579 questions
Windows for business Windows Server User experience PowerShell
{count} vote

1 answer

Sort by: Most helpful
  1. spaceman sp 16 Reputation points
    2022-08-02T20:06:27.247+00:00

    I have been working with MS support on this. I opened the case as the end on May 2022 and they finally got back to me on Aug 1st 2022.
    They gave me a modified request body:

    {  
      type: "Usage",  
      dataset: {  
        "granularity": "monthly",  
        "aggregation":{  
          "totalCost":{  
            "name":"Cost",  
            "function":"Sum"  
          }  
        }  
      },  
      timeframe: "Custom",  
      "timePeriod": {  
        "from": "2022-08-01",  
        "to": "2022-08-31"  
      }  
      
    

    and it worked.

     $forecast = Invoke-RestMethod -Uri $forecasturi -Method post -Headers $authHeader -body $body    
      
     $forecast.properties.rows  
    430.2517981776787  
    2022-08-01T00:00:00  
    Forecast  
    USD  
    

    So I think I can play with, but it does give the forecast.

    I do not understand why Azure has documentation for this on-line and then you say it's not supported.

    Roger

    1 person found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.